can someone explain this to me?

i have been trying to find a way to only allow certain inputs by the user to stop the program going crazy when i ask for a number and the user inputs a character(thus going crazy)
this method works but i dont understand why it does, and rather than copy and pasting it every time i need it, i want to know why

Plus my program asks a lot of questions allowing a lot of times where the user is able to make the program go crazy,

is there a more simple or shorter method than this for multiple use of this feature?

also what does <limits> allow the program to use?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <limits>
using namespace std;

int main()
{
    bool valid = false;
    int input;
    while (!valid)
    {
        if(cin >> input)
        {
            //this checks whether an integer was entered
            if(input < 6 && input > 0)
                valid = true;//then we have to see if this integer is in range
        }
        else
            cin.clear(); //some cleaning up

        cin.ignore(numeric_limits < streamsize > ::max(), '\n');//empty input stream

        if(!valid)
            cout << "this input is not valid\n";
    }
    cout << input << " is between 1 and 5\n";
    cin.get();
    return 0;
}
Usually I just read the input as a string then try to convert it to the type I'm looking for.
Something like this: http://cplusplus.com/articles/Sy86b7Xj/
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.3
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.4

I don't necessarily agree with always taking a string input, but that is certainly one way to do it. Read the above and some of the other FAQs. If you enter a character such as 'a' or 'b', I think that your code should execute the else path due to the if statement. That program worked for me. What do you mean by "it goes crazy"?

If I were you, I'd combine the if statements like so
if(cin >> input && input < 6 && input > 0)

That way the clear happens regardless of why it fails. As far as why the if statement works, please refer to the FAQ lite. I can't explain it any better then the author.
Last edited on
how is this suppose to convert a string of integers into an int?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    string Text = "456";
    int Result;

    stringstream convert(Text);

    if ( !(convert >> Result) )
        Result = 0;
}
crazy meaning infinte looping
This program requires <limits> because it uses the numeric_limits template.

I believe this line:

cin.ignore(numeric_limits < streamsize > ::max(), '\n');//empty input stream

tells cin to skip some characters (up to the maximum stream size) until a newline character is found.



Edit: Bah! I should have clicked the link from Duoas. :D
Last edited on
Topic archived. No new replies allowed.