#I am tring to make a program to try out the all functions of c string 我在这个程序中接受了两个输入第一个输入被接受但是第二个输入现在不接受我该如何更正我的程序
#include<iostream>
#include<cstring>
using namespace std;
int main(){
char a[100];
char bstring[50]="how are you\n";
char c[100];
cout<<"input string 1\n";
cin.get(a,100);
cout<<"input string 2\n";
cin.get(bstring,50);
strcpy(c,a);
cout<<" after cpy a into c \n"<<c;
strcat(a,bstring);
cout<<" after cat b into a \n"<<a;
cout<<"length of a \n"<<sizeof(a);
if(strcmp(a,bstring)== -1){
cout<<"str1 is smaller \n";
}else if(strcmp(a,bstring)==0){
cout<<"both are equal \n";
}else if(strcmp(a,bstring)== 1){
cout<<"str1 is grater \n";
}
return 0;
}
读取字符串后,您需要另一个
cin.get();
。这将消耗行尾字符。否则,行尾将是下一个字符串。或者使用 cin.getline()
读取字符串并一次性消耗行尾。
请注意,无论字符串有多长,
sizeof(a)
始终为 100。正如评论中提到的,strcmp应该与<0 and >0.进行比较