提示用户输入正数,并继续提示用户输入正数C++
//review3
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
while (number < 0)
{
cout << "Enter a positive number" << endl;
}
if (number > 0)
{
cout << "Awesome job!" << endl;
}
return 0;
}
这是我的代码。我从另一个开始,但如果用户输入负数,程序就会关闭。我把它改成了一个while循环,并陷入了一个无限循环。之前我有一个if和else if声明。我需要继续提示用户,直到他们在C++中输入正数。提示用户输入正数,并继续提示用户输入正数C++
你的while()
循环不会继续提示输入,这就是为什么你得到一个无限循环 - 因为number
永远不会改变!
你可以把输入操作到while()
循环是这样的:
while (cin >> number && number < 0)
{
cout << "Enter a positive number: " << endl;
}
if (cin)
{
cout << "Awesome job" << endl;
}
因此,循环中的用户将被提示输入的每个迭代过程中。
之后我们检查了cin
的状态,以确保上述循环由于无效输入(或根本没有输入)而没有停止。
如果用户输入“abc”,会发生什么情况。我将循环条件设置为while(!(std :: cin >> number)|| number 2014-11-09 00:46:46
当然,如果他使用这种解决方案,他应该在进入循环之前将'number'初始化为负值。 – 2014-11-09 00:48:03
@JamesKanze好主意。但是当你说“在循环之后进行额外的检查”时,你的意思是像我的'if(cin)'?或者它应该是'if(!cin.eof())'? – 0x499602D2 2014-11-09 01:07:52
#include <iostream>
#include <string>
#include <cstring>
int main()
{
while(true)
{
std::cout << "Pleaase enter a positive number." << std::endl;
std::string buf;
int x = -255;
std::cin >> buf;
x = std::atoi(buf.c_str());
if(x > 0)
{
break;
}
}
std::cout << "Awesome Job!" << std::endl;
}
未定义的行为,如果用户输入'“abc”'。 – 2014-11-09 00:49:49
我相信这可以通过正确初始化x来解决。让我们解决这个问题! – yash101 2014-11-09 04:18:34
因此,而不是未定义的行为,你有一个无限循环。 – 2014-11-10 09:21:41
你也可以做这个片段。使用#include <ctype.h> or <cctype>
while(1){
cin>>number;
if(number<0 || isalpha(number)) return 0;
cout<<"Awesome Job";
}
如果用户输入'“abc”',则不确定的行为。 – 2014-11-09 00:50:12
#include <iostream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
if (number < 0) {
cout << "Enter a positive number" << endl;
}
else {
cout << "Awesome job!" << endl;
}
return 0;
}
更多未定义的行为。 – 2014-11-09 00:50:42
只需将cin >> number;在while循环中。在cout声明下面。 – antorqs 2014-11-09 00:05:38
那么你的问题是什么?你只是停留在告诉我们你的问题是什么。 – 2014-11-09 00:34:10