我正在尝试比较一个琐事程序的两个字符串,一个由用户输入,另一个从节点访问。比较在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
答案 0 :(得分:1)
getline(cin, userAnswer)
保留\n
。您可以考虑使用类似以下内容的方法修剪字符串
getline(cin, userAnswer);
userAnswer.erase(userAnswer.find_last_not_of("\n\r") + 1);
不能保证这是答案,但我已经碰到了几次这只是一个尾随\n
或\r
。
答案 1 :(得分:0)
在比较之前对字符串进行一些boost::trim()
比较,看看是否有帮助。