-
Multiple Inputs
I know this is probably a really easy question, but my teacher failed to mention how to do it, so here goes.
I'm making a simple program that tells a user if a sequence of given numbers are even or odd. Here's what the program should look like:
Code:
Enter a sequence of numbers (0 to quit): 12 4 19 3 0
12 is even
4 is even
19 is odd
3 is odd
I've gotten the program made, except my output stops at "12 is even".
My question is, how do I get my program to loop through all of the numbers and stop at 0?
I tried using a while loop,
But, it just looped "12 is even" over and over.
-
Re: Multiple Inputs
Copy and paste the code please. It helps us understand your problem better.
-
Re: Multiple Inputs
Here's the code.
Just note that I pulled out the While (x != 0) loop because it was making an infinite loop.
I just need to know how to accept the multiple inputs... do I need to do something like cin >> x1 >> x2 >> x3 etc?
Code:
int main ()
{
int input;
cout <<"Enter a sequence of numbers (0 to quit): ";
cin >> x;
if (x != 0)
{
if (x % 2 == 0)
{
cout << x << " is even" << endl;
}
else if (x % 2 != 0)
{
cout << x << " isn't even" << endl;
}
}
}
-
Re: Multiple Inputs
Well you want your 'cin >> x' inside the while loop so it will keep accepting numbers for the variable. You don't need your 'input' variable, and whenever you have a variable inside your while statement, it has to be initialized to a number (i usually set it as -1).
-
Re: Multiple Inputs
Ah, got it, I needed a Do...While loop rather than a While loop. Thanks!
-
Re: Multiple Inputs
In the original example I didn't see any loop at all. It looks like you are on the right track but let me suggest another FAQ site that you can use to improve upon whatever you ended up with. It has some ideas for handling some of the other common errors that you might encounter such as what happens if a user enters a letter instead of a number? I wish that this FAQ existed when I was in college. As a beginner I struggled with some of these I/O stream issues and remember that my instructor was not helpful at explaining the most common problems that I was running into.
http://www.parashift.com/c++-faq-lite/input-output.html
-
Re: Multiple Inputs
x is undeclared. Did you try to compile the code you posted??