strcmp 是用来比较两个C字符串(即char数组),参数类型都是char*,所以不能直接拿string作为参数。
可以用 例题:编写一个程序,它使用char数组和循环来每次从键盘读取一个单词,直到用户输入done为止。随后该程序指出用户输入了多少个单词。 #include #include int main(){ using namespace std; const int size = 20; char ch[size] ; int i = 0; cout<<"Enter words(to stop with word done)"< cin>>ch; while (strcmp(ch,"done")) /*字符串之间的比较, 相同返回0. 左<右,返回负数。cmp是compare的缩写*/ { i++; cin>>ch;} cout<<"You entered a total of "<
} 下面是用string类完成上述例题的代码 #include #include using namespace std; int main(){ string str; int i = 0; cout<<"Enter words (to stop,with word done)"< cin>>str; while(str != "done")//注意和上面的区别 { cin>>str; i++; } cout<<"You entered a total of "<
return 0; }扩展资料:
strcmp 是用来比较两个C字符串(即char数组),参数类型都是char*,你拿两个string类型的变量作为参数,当然出错啦。比较两个string类型变量是否相等,不需要用strcmp,直接用==就可以了。
如果没有记错
所以不能直接拿string作为参数
可以直接include
或者使用
用 strncmp()比较。 string 变 char 用 s1.c_str():
#include
using namespace std;
#include
int main()
{
string s1="12:00:00", s2="12:00:10";
int ret;
if (strncmp(s1.c_str(),s2.c_str(),5)==0) ret=1; else ret=0;
cout << "ret=" << ret << endl;
return 0;
}
你#include
我希望你能改为下面的比较好:
#include
#include
试试看行不行!
希望能帮助你!