我目前正在从事编程工作,在检查用户输入的内容时遇到了麻烦。该程序仅在其中输入两个正数,但是当我输入一个字符(例如“ a”作为我的第一个“数字”)时,程序会接受它并将其输出,就像我输入零一样。它应该输出“无效数字:数字必须为正整数”。有人可以告诉我我在做什么错吗?谢谢!
XML
答案 0 :(得分:0)
if (firstNum==x || secondNum==x)
cout<< "\nError: Invalid number: Numbers must be positive integer.\n";
此测试是错误的x尚未初始化,并且没有任何意义。.plus您已使用该标志来测试我假设的失败输入情况,因此您的代码应像这样
#include <iostream>
using namespace std;
int main()
{
//Displays information of what program will do
cout << "Practice with iterations\n\n"
<< "The function of this program is, given 2 positive numbers, the"
<< " program";
cout << "\nwill display the following\n\n";
cout << "\t1. All even numbers between firstNum and secondNum.\n"
<< "\t2. All odd numbers between firstNum and secondNum.\n"
<< "\t3. Sum of all even numbers between firstNum and secondNum.\n"
<< "\t4. Sum of all odd numbers between firstNum and secondNum.\n"
<< "\t5. All prime numbers between firstNum and secondNum.\n"
<< "\t6. Factorial of the secondNum.\n"
<< "\t7. The numbers and their squares between firstNum and "
<< "secondNum." << endl;
//Declare first and second number variables
int firstNum;
int secondNum;
bool flag = true; //Set to true
//Ask user to input values
cout << "\n\nEnter the first number:\t\t";
cin >> firstNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
cout << "Enter the second number:\t";
cin >> secondNum;
if (cin.fail())
{
cout << "lol" << endl;
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
if (flag) {
if (firstNum > secondNum)
cout << "\nError: First number must be < second number.\n";
else if (firstNum < 0 || secondNum < 0)
cout << "\nError: Invalid number: Number must be positive.\n";
else
{
cout << "\nYou entered: " << firstNum << " and " << secondNum;
}
}
else cout << "Error input" << endl;
return 0;
}
答案 1 :(得分:0)
如果在读取输入时出现错误,则说明您已正确说明了第一步-清除输入流并清除cin
的错误状态。您缺少的是将有效内容读入变量。为此,您需要一个循环。
while (true )
{
//Ask user to input values
cout<< "\n\nEnter the first number:\t\t";
// Try to read the input. If it is successful, break out of the loop.
if ( cin>> firstNum )
{
break;
}
// Clear the error flag. Clear the input stream. Try again.
cin.clear();
cin.ignore(256,'\n');
}
对第二个数字做同样的事情。