检查有效的 CIN 输入时出现问题
Problems checking for valid cin input
我的代码:http://pastebin.com/qjFd6KXb
我有一个课程作业,要求我创建一个程序,该程序将输出一个简单的乘法问题,用户必须在三次或更少的尝试中回答。其中一个要求是程序检查用户猜测是否为有效数字。我的教授希望我们在代码中使用此方法:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char c;
bool valid = false;
int i;
while (!valid)
{
cout << "Enter an int " << endl;
cin >> i;
valid = true;
if (cin.peek() != 'n' || cin.fail()) // checks if the input data was correct or not
{
valid = false;
cin.clear(); // clears the error flags
cin.ignore(100, 'n'); // ignores up to 100 characters in the cin stream
}
}
}
我的问题出现在我的代码的第 57 行左右。没有额外的 while 循环和 if 语句来检查正确性,它运行良好。然而,无论我尝试什么,当我实现该部分时,它要么变成无限循环,要么不可能获胜。如果有人能让我知道这有什么问题,我将不胜感激,因为我一生都无法弄清楚这个问题。
只是简单地
看了一下你的代码。我认为
tries = tries + 1; // Adds one to the tries counter
在错误的范围内
while ((choice != 1) || (choice != 1) || (choice != 1));
cout << "Try to solve the problem!n"; // Provides instruction to the user.
while ((result != guess) && (tries < maxtries))
{
}
tries = tries + 1; // Adds one to the tries counter
}
应该是
while (choice != 1);
cout << "Try to solve the problem!n"; // Provides instruction to the user.
while ((result != guess) && (tries < maxtries))
{
tries = tries + 1; // Adds one to the tries counter
}
}
您的检查可以像这样实现:
std::cin >> i;
while( std::cin.fail() ) {
std::cout << "Bad InputnEnter an Integer, foo: ";
std::cin.clear();
std::cin.ignore('256','n');
std::cin >> i;
}
我不确定你为什么要达到顶峰并寻找终点
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 编写时C++中的输入重定向问题
- 输入std::数组时出现问题
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- 用户输入字符串的文件附加问题..C++
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 我应该如何在C++中使用结构体解决输入失败的问题?
- 我遇到使用 c++ 逐行读取输入文件的问题
- 在 2D 矢量中获取多个输入时出现问题
- 不确定出了什么问题(字符串输入)
- 在C++中读取 unicode 输入时出现问题
- 函数,从问题中获取输入,并在主函数中使用该输入
- c++中重载输入运算符的问题
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- 从标准输入读取多个类型时出现问题
- visual studio 2008 - c++问题输入