Reputation: 81
I'm writing a simple program that needs to take in the number of elements a user wants in their array. The program then needs to read in the elements of the array and display the output. Some rules of the program are:
For some reason I keep getting the output of the array plus the previous question relayed to the user.
EX:
#include <iostream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 20;
int inputOne = 0;
int arrayOne[ARRAY_SIZE];
cout << "Enter how many numbers you'd like to read in up to 20: ";
cin >> inputOne;
//Input the numbers
for (int input = 0; input < inputOne; input++)
{
cout << "Enter in the numbers: ";
cin >> arrayOne[input];
}
//Display the array
for (int input = 0; input < inputOne; input++)
cout << arrayOne[input];
cout << endl;
system("pause");
return 0;
}
Upvotes: 3
Views: 161
Reputation: 1
I was astonished to see the output of your program. The Problem is only when you are entering the number. if you press enter instead of space then your code will produce expected result.enter image description here
Upvotes: -1
Reputation: 63
cin read from the stream, up to the whitespace. with your input your are filling the stream.
when you 1 2 3 4 5 <hit return>
cin reads 1
and stops, the while loop goes for another cin call but only the 1
has been consumed so cin finds the 2
and consume it. and so on.
this bein clarified, you don't have a real problem to fix.
If you want the numbers to be entered like you did in your example just while cin >> arrayOne[i++]
.
If you want to be asked for every number, just clear the stream after you read the first number with cin.ignore()
to be sure input as yours only takes the first number.
Upvotes: 0
Reputation: 1075
This output is correct. When you use cin for an integer, it waits for an integer, and once it gets one the loop continues. Hence when you type 1 2 3 4 5 you're feeding multiple entries into the loop at a time, and each time the loop is continuing because the next integer is already there. You might solve this by adjusting your input:
Enter in the numbers: 1 [RETURN]
Enter in the numbers: 2 [RETURN]
Enter in the numbers: 3 [RETURN]
Enter in the numbers: 4 [RETURN]
Enter in the numbers: 5 [RETURN]
Upvotes: 2