当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了
Unable to compare two strings when one of them is from cin. What is wrong here?
void Display::getInput(){
cout << endl << endl << "Enter Command: ";
char input[MAX_LENGTH];
cin >> input;
if (input == "start"){
startMenu();
}
我得到了这个错误,但我不确定为什么,因为我总是可以使用这个语法进行比较。。
Display.cpp:在成员函数"void Display::getInput()"中:
Display.cpp:20:16:warning:与中的字符串文字结果进行比较如果(input="start"){
要比较C样式字符串,需要使用strcmp
。否则,将input
更改为字符串(std::string
),而不是字符数组。您正在比较两个指针,其中一个指向文字,另一个指向数组,因此它们永远不可能相等。
您不能像那样比较C风格的字符串,而是使用strcmp
进行比较,成功时返回0
,失败时返回非零。
或者您可以使用类string
:
int main(){
char szInput[100];
std::cin.getline(szInput, 100);
const char* szTest = "Hello";
if(!strcmp(szInput, szTest))
std::cout << "Identical" << std::endl;
else
std::cout << "Not identical" << std::endl;
std::string sInput;
std::getline(std::cin, sInput); // getline for white-spaces
std::string sTest = "Welcome there!";
if(sTest == sInput)
std::cout << "Identical" << std::endl;
else
std::cout << "Not identical" << std::endl;
return 0;
}
- 我使用
getline
而不是cin
来计算空白字符数
相关文章:
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 字符串比较中的意外输出
- 如何执行不区分大小写的字符串比较?
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- <<运算符优先级与字符串比较
- ">"运算符和"<"运算符如何进行字符串比较?
- Qt C++11 字符串通过子字符串比较列出交集
- std::out_of_range字符串比较中的异常
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 字符* 与uint8_t的字符串比较
- 用字符串 c++ 比较对向量的元素
- 使用循环进行词典字符串比较
- 如何为C++映射创建自己的字符串比较对象
- 不带比较()的字符串比较
- 与 IF 语句C++的字符串比较?
- 字符串比较在与变量一起使用时给出不同的输出
- 更快的字符串比较排序,用于唯一()
- C 字符串比较“祝您好运”&gt;“再见”
- C 奇怪的行为和字符串比较
- 子字符串与 std::memcmp 或字符串::比较的比较