这是比较 s2 和 s1 的代码,如果它们相同,则返回 0 和一些其他选项,但是 while 循环不能结束,我找不到它的问题,我唯一知道的是如果我转换 char * s2 转换为 const char* s2 它将正常工作。
#include <iostream>
using namespace std;
int cmp(char*,char*);
int main()
{
char* s1;
cout << "Please Enter First Word: "; cin >> s1;
char* s2;
cout << "Please Enter Second Word: "; cin >> s2;
cout << "The Result is: " << cmp(s1,s2) << endl;
return 0;
}
int cmp(char* s1, char* s2)
{
int i=0;
while (*(s2+i)!=0)
{
if (*(s2+i)>*(s1+i)) return 1;
if (*(s2+i)<*(s1+i)) return -1;
i++;
}
return 0;
}
最佳答案
您有未定义的行为。您没有分配任何空间来存储字符串(您没有初始化 s1
或 s2
以指向任何内存)。
我建议改用std::string
;它管理自己的内存问题。
关于c++ - Char* 和 While Loop 不能相互配合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9725694/