【问题标题】:C++ String comparison not working as intendedC++ 字符串比较未按预期工作
【发布时间】:2015-03-14 00:37:38
【问题描述】:

我正在尝试比较一个琐事程序的两个字符串,一个由用户输入,另一个从节点访问。比较在 IF 语句中,并且总是返回 false。以下是用于此功能的代码。变量 userAnswer 和 answer 都是字符串类型。

cout << "Question: " << cur_ptr->question << endl;
cout << "Answer: ";
getline(cin, userAnswer);
if (userAnswer == cur_ptr->answer) {
    cout << "Your answer is correct. You receive " << cur_ptr->points << " points." << endl;
    totalPoints += cur_ptr->points;
}
else {
    cout << "Your answer is wrong. The correct answer is: " << cur_ptr->answer << endl;
}
cout << "Your total points: " << totalPoints << endl << endl;
cur_ptr = cur_ptr->next;

每当我的程序运行时,它都会生成这样的输出

Question: How long was the shortest war on Record? (Hint: how many minutes)?
Answer: 38
Your answer is wrong. The correct answer is: 38
Your total points: 0

【问题讨论】:

  • 我无法重现这个。也许字符串包含一些空格或奇怪的字符? ideone.com/xnYHYg

标签: c++ string if-statement compare


【解决方案1】:

getline(cin, userAnswer) 保留\n。您可以考虑使用以下内容修剪字符串

getline(cin, userAnswer);
userAnswer.erase(userAnswer.find_last_not_of("\n\r") + 1);

不能保证这就是答案,但我已经遇到过几次,它只是一个尾随 \n\r

【讨论】:

  • 谢谢!!这确实适用于我的代码。快速的问题。那行代码中 +1 的目的是什么。
  • @Neal 你应该找出多余的空格被插入到字符串中的位置并阻止它。
  • find_last_not_of 确实像它听起来的样子。所以最后一个不是\n\r 的字符是您需要的字符。例如。 std::string s("Hello, World!"); s.erase(s.find_last_not_of("!")); 会给你“Hello, Worl”。在这种情况下,erase 采用 size_t 等于您要保留的字符数。
【解决方案2】:

在比较之前对要比较的字符串做一些boost::trim(),看看是否有帮助。

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    相关资源
    最近更新 更多