【发布时间】:2018-05-18 01:57:58
【问题描述】:
我正在做一个乘法练习程序。正如我的标题所说,如果我在控制台中输入一个字母而不是数字,它会在第一个上说正确,但在其余部分上不正确。即使你不触摸键盘,它仍然会吐出错误的内容。
ans = table * i;
std::cout << table << " * " << i << " =" << std::endl;
std::cin >> input;
if(input == ans)
{
std::cout << "Correct! " << ans << std::endl;
}
else
{
std::cout << "Incorrect, the answer was " << ans << std::endl;
input = 0;
ans = 0;
}
}
希望这能让您了解代码中发生的情况。这是输出。
Enter the table you'd like to learn.
5
Enter the amount of multiples
3
5 * 0 =
s
Correct! 0
5 * 1 =
Incorrect, the answer was 5
5 * 2 =
Incorrect, the answer was 10
5 * 3 =
Incorrect, the answer was 15
我能做些什么来解决这个问题?感谢您的输入。
【问题讨论】:
-
ans、table、i、input都是ints,对吧? -
正确的@TheObscureQuestion,它们都是整数。
-
发生匹配失败时,不再读取字符,输入的任何字符都留在输入缓冲区中(
stdin)未读只是等着在你的循环的下一次迭代中再次咬你 -- 除非你正确处理失败并考虑任何未读的字符。
标签: c++ cin multiplication