C++字符串比较 strcmp

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string word="jia";
string word1="jie";
cout<<strcmp(word,word1);
}
为什么cout<<strcmp(word,word1);这行编译不能通过呢?

strcmp 是用来比较两个C字符串(即char数组),参数类型都是char*,所以不能直接拿string作为参数。

可以用<cstring>,但写成cout<<strcmp(word.c_str(), word1.c_str()); string类型的c_str()函数会将string中的字符串转为const char*

扩展资料:

例题:编写一个程序,它使用char数组和循环来每次从键盘读取一个单词,直到用户输入done为止。随后该程序指出用户输入了多少个单词。

#include <iostream>

#include<cstring>

int main(){

using namespace std;

const int size = 20;

char ch[size] ;

int i = 0;

cout<<"Enter words(to stop with word done)"<<endl;

cin>>ch;

while (strcmp(ch,"done"))

/*字符串之间的比较, 相同返回0. 左<右,返回负数。cmp是compare的缩写*/

{

i++;

cin>>ch;}

cout<<"You entered a total of "<<i<<" words."<<endl;

}

下面是用string类完成上述例题的代码

#include<iostream>

#include<string>

using namespace std;

int main(){

string str;

int i = 0;

cout<<"Enter words (to stop,with word done)"<<endl;

cin>>str;

while(str != "done")//注意和上面的区别

{

cin>>str;

i++;

}

cout<<"You entered a total of "<<i<<" words."<<endl;

return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-07-12
strcmp 是用来比较两个C字符串(即char数组),参数类型都是char*,你拿两个string类型的变量作为参数,当然出错啦。比较两个string类型变量是否相等,不需要用strcmp,直接用==就可以了。本回答被提问者采纳
第2个回答  2011-07-12
如果没有记错 <cstring>里定义的strcmp的参数是char*
所以不能直接拿string作为参数
可以直接include <string>, string里面也定义了strcmp,而且是以string为参数的
或者使用<cstring>,但写成cout<<strcmp(word.c_str(), word1.c_str()); string类型的c_str()函数会将string中的字符串转为const char*
第3个回答  2018-05-31
用 strncmp()比较。 string 变 char 用 s1.c_str():
#include <iostream>
using namespace std;
#include <cstring>
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;
}
第4个回答  2011-07-12
你#include<cstring>中的有错,是#include<string>,里面没有c。
我希望你能改为下面的比较好:
#include<iostream.h>

#include<string.h>
试试看行不行!

希望能帮助你!