C++字符串比较 strcmp

2025-03-21 03:54:54
推荐回答(5个)
回答1:

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

可以用,但写成cout<

扩展资料:

例题:编写一个程序,它使用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;

}

回答2:

strcmp 是用来比较两个C字符串(即char数组),参数类型都是char*,你拿两个string类型的变量作为参数,当然出错啦。比较两个string类型变量是否相等,不需要用strcmp,直接用==就可以了。

回答3:

如果没有记错 里定义的strcmp的参数是char*
所以不能直接拿string作为参数
可以直接include , string里面也定义了strcmp,而且是以string为参数的
或者使用,但写成cout<

回答4:

用 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;
}

回答5:

你#include中的有错,是#include,里面没有c。
我希望你能改为下面的比较好:
#include

#include
试试看行不行!

希望能帮助你!