0

I have my programs asking for 3 inputs in 3 seperate while loops. How come if i enter

4 2 5 with spaces it fills in all the inputs input1,input2,input3? Is there a way to make it give an error if this happens?

int input1 = 0
while (!(cin >> input1) || input1 < 0)
    {
        if (!cin)
        {
            cout << "Please enter a positive value: ";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

int input2 = 0
while (!(cin >> input2) || input2 < 0)
    {
        if (!cin)
        {
            cout << "Please enter a positive value: ";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

int input3 = 0
while (!(cin >> input3) || input3 < 0)
    {
        if (!cin)
        {
            cout << "Please enter a positive value: ";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }
tyrone 251
  • 355
  • 1
  • 4
  • 14

1 Answers1

2

You can use std::getline to read the entire line (including spaces) in one shot, and then you can check if a whitespace is found in the string using std::string::find:

std::string in;
std::getline(std::cin, in);
if (in.find(' ') != std::string::npos) {
    // whitespace found / error
} else {
    // no whitespace found
}
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • why not `std::string in = std::cin.getline();`? – SHR Mar 10 '14 at 22:54
  • I see the point. I think you should add also `stringstream` and convert the input to int in the else. – SHR Mar 10 '14 at 23:00
  • 1
    @SHR, I can't find the documentation for `std::basic_istream::getline` with no arguments. – Shoe Mar 10 '14 at 23:01
  • you got my vote... you need to give it buffer and string max size. – SHR Mar 10 '14 at 23:02
  • @user3398034, you can then use [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol) to convert your string to int (if it doesn't contain whitespaces). – Shoe Mar 11 '14 at 01:58
  • Im having trouble implementing this. Could you show me an example with one of my while loops? – tyrone 251 Mar 11 '14 at 01:59
  • my compiler doesnt support stoi :( – tyrone 251 Mar 11 '14 at 02:07
  • @user3398034, what line do you use to compile your program? – Shoe Mar 11 '14 at 02:11
  • @user3398034, you should search trought the settings and see if you can add a compiler flag. If you can you should add `-std=c++11` and `-stdlib=libc++` as flags – Shoe Mar 11 '14 at 02:12
  • @user3398034, alternatively [follow this answer](http://stackoverflow.com/a/7663741/493122). – Shoe Mar 11 '14 at 02:15