提示用户输入正数,并继续提示用户输入正数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++

+1

只需将cin >> number;在while循环中。在cout声明下面。 – antorqs 2014-11-09 00:05:38

+0

那么你的问题是什么?你只是停留在告诉我们你的问题是什么。 – 2014-11-09 00:34:10

你的while()循环不会继续提示输入,这就是为什么你得到一个无限循环 - 因为number永远不会改变!

你可以把输入操作到while()循环是这样的:

while (cin >> number && number < 0) 
{ 
    cout << "Enter a positive number: " << endl; 
} 

if (cin) 
{ 
    cout << "Awesome job" << endl; 
} 

因此,循环中的用户将被提示输入的每个迭代过程中。

之后我们检查了cin的状态,以确保上述循环由于无效输入(或根本没有输入)而没有停止。

+1

如果用户输入“abc”,会发生什么情况。我将循环条件设置为while(!(std :: cin >> number)|| number 2014-11-09 00:46:46

+1

当然,如果他使用这种解决方案,他应该在进入循环之前将'number'初始化为负值。 – 2014-11-09 00:48:03

+0

@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; 
} 
+1

未定义的行为,如果用户输入'“abc”'。 – 2014-11-09 00:49:49

+0

我相信这可以通过正确初始化x来解决。让我们解决这个问题! – yash101 2014-11-09 04:18:34

+0

因此,而不是未定义的行为,你有一个无限循环。 – 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"; 
} 
+2

如果用户输入'“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; 
} 
+0

更多未定义的行为。 – 2014-11-09 00:50:42

,如果你得到数或弦here

确保在这种情况下,你应该得到输入字符串变量可以检查。如果要将其转换为整数,可以使用std::stoi