Need help!

I just got this piece of code from the internet and I'm curious on how does the condition for the both whiles work also, how does continue work/what does it do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 for (i = 0;i <= 2; i++)
    {

        cout<<"Enter a number: ";
//How does this work from here
		while(!(cin>>number[i]))
		{
          cin.clear();
          
     			  while(cin.get()!='\n')
     			  continue;
				  {												
		 		    cout << "\nINVALID ENTRY!! ";            
          			cout << "\n\nEnter a number: ";
  		 	   	  }

             }
//to here

    }
It's saying that it's going into a loop (for), initializing (or setting) the variable i to 0, then asking if 0(i) is less than or equal to 2. I'll get to the i++ in a moment.
So, if 0 is <= 2 is true, the loop will continue. If it is false, everything between the loop's {} are skipped.
It's true, so the statements in the loop are processed.
It asks the user to enter a number. The next is a loop that tests a condition before it iterates. While the input of the number is !(not), which means, if the input is anything other than a 0, it will terminate. Because all numbers other than 0 are considered true, a statement like while(2), would mean it's saying while(true). If the person enters a 0 for the number, it's false and does not perform the statements in the while loop's {}. cin.clear(); clears the buffer of any error statements. For example, someone may put in 1x. It's not a valid statement, so the cin.clear will clear it out. While cin.get() is NOT EQUAL to a newline character, Make them enter another number.

So basically what this does is it asks a user to enter a number. It validates the input making sure that they do not input anything other than a number. When or if they do, it displays a message and loops back for the user to enter a number until it's a valid input.
A more conventional approach uses cin.ignore() rather than a second loop.
1
2
3
4
5
6
7
8
9
10
11
12
    int number; 
    cout<<"Enter a number: ";
    
    while (!(cin>>number))          // Attempt to get an int and test the result
    {
        cin.clear();                // reset error flags
        cin.ignore( 1000, '\n' );   // clear the invalid characters from the input buffer
            
        cout << "\nINVALID ENTRY!!\n\nEnter a number: ";
    }

    cout << "The number was: " << number << endl;


Here the cin>>number is executed. If the input was not a valid integer, the condition will be true, so the body of the while loop is executed.
It needs to reset the fail flag (which was set for cin because the operation failed) and then discard the unwanted characters from the buffer.

The first example used this instead of cin.ignore():
1
2
while (cin.get()!='\n')
    continue;

Here the keyword continue simply means go back to the start of the current loop and continue execution from that point.
Chevril, I could easily look this up but I thought I'd ask you instead. Can you explain what the arguments in cin.ignore are? Does it mean to check 1000 characters for the instance \n? Just guessing, I saw that a lot trying to look up how to input validation and none of what i read put it in simple terms.

Also, could you do the same in reverse for alpha validation or would it use the variable's ASCII code? for example,

1
2
3
4
5
6
7
8
9
10
string name;

while (cin >> name)
     {
        cin.clear();
        cin.ignore(1000, '\n');
     
        cout << "Sorry, Please enter a name, no numbers are allowed.\n";
      }


http://www.cplusplus.com/reference/istream/istream/ignore/

In my example, I specified to ignore up to 1000 characters, or until a newline character is found (whichever comes first).

That logic won't work for std::string, since all characters are valid for a string so the cin>>name will never fail. You could test the string yourself by checking each character using a function such as isalpha() http://www.cplusplus.com/reference/cctype/isalpha/
Okay, gotcha =)

I had to use an algorithm like that in logic, so that's not too bad to only have to use it for strings. Thanks!
What does the '\n' mean? why do you have to use specifically that instead of other characters? Still confused.
'\n' is the character representing the newline character, i.e. what starts the text on the next line. '\n' is used in calls like cin.ignore(1000, '\n'); or getline(FOO, BAZ, '\n'); to indicate that you want to stop when the line stops and goes to a new line (basically just the end of a line).
Regarding '\n', see "Character and string literals" on this tutorial page:
http://www.cplusplus.com/doc/tutorial/constants/

If you are struggling with basic concepts, it might be a good idea to go through the tutorial pages from the start. http://www.cplusplus.com/doc/tutorial/
THANKS!
Topic archived. No new replies allowed.