0

Define an integer vector and get several input from keyboard, then display the numbers in the vector. The while loop is required to write the display loop. I am having trouble turning my program into a while loop and getting mistakes. Please help.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
int x;
vector<int> temp;
cout<<"Please enter several integer numbers."<<endl;
while (cin>>x)
{
temp.push_back(x);
}
typedef vector<int>::size_type vec_sz;
vec_sz n=temp.size();
vec_sz i=0;
while(i<n)
{
cout<<temp[i]<<endl;
++i;
}
return 0;
}
2
Contributors
1
Reply
26
Views
4 Years
Discussion Span
Last Post by Banfa
0

Your problem is in the while loop at line 9. The thing is that cin is always going to return ok (true) while it can perform the operation you have requested so the only way to break this loop is to input data that can't be converted to a number, a letter for example so if you input the string "4 5 6 7 8 9f" for example you code works fine outputing the list of numbers.

You could change the text at line 8 to read "Please enter several integer numbers, enter q when finished." without changing anything else to get a program that works as instructed. The other alternative is to ask how many numbers the user wishes to input first and then when you have got that many numbers to stop asking for any more.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.