【问题标题】:C++ If-else statement using strings and comparing strings使用字符串和比较字符串的 C++ If-else 语句
【发布时间】:2016-10-21 10:26:49
【问题描述】:

当我输入 (Im qwerty) 作为 (y) 时,程序显示“您的帐户已被停用”而不是“您的密码不正确”。我搜索了相同的问题,但 const. char 和使用 strcmp 对我来说太复杂了,我的导师不使用那种代码。我很想知道我必须做什么才能使我的程序正确。 (提前Tnx)

#include <iostream>

using namespace std;

int main () {
string y;
cout << "Enter Icode: ";
cin >> y;


if (y == "Im qwerty")
    cout << "Your password is incorrect.";

else
    cout << "Your account has been deactivated.";



cin.get();
return 0;

}

【问题讨论】:

  • 但是当 y = "I'm qwerty" 时,它不是 "I'm robbee" - 那你为什么会期望它说“不正确”呢?
  • "I'm qwerty" 不等于 "Im robbee",自然应该去 else 条件
  • strcmp 用于 C,使用 y.compare("Im qwerty") != 0)
  • 你问的问题可以用调试器解决;我可以建议您阅读this,这将有助于您在未来解决其他问题
  • 您是否考虑打印出y 的值来查看它是什么? “我的东西有问题”然后看看这个东西

标签: c++ if-statement


【解决方案1】:

问题是cin &gt;&gt; y; 读取一个单词,而"Im qwerty" 有两个单词。换句话说,这个程序总是输出"Your account has been deactivated.",因为一个词永远不会匹配两个词。

如果您想阅读多个单词,最简单的方法是阅读整行,例如将cin &gt;&gt; y; 替换为getline(cin, y);

【讨论】:

  • 非常感谢先生。 @马克西姆
  • @MaximEgorushkin:我不是你的“甜心”。
猜你喜欢
  • 2018-07-10
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多