C++ 字符串比较不按预期工作

C++ String comparison not working as intended

我正在尝试比较琐事程序的两个字符串,一个由用户输入,另一个从节点访问。比较是在 IF 语句中进行的,并且总是 returns 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

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

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

不能保证这就是答案,但我已经 运行 讨论过几次,只是尾随 \n\r

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