Vector to read int

Here's a problem of vector that I think I've solved:

Write a program to read a sequence of ints from cin and store those values in a vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Write a program to read a sequence of ints from cin and store those values in a vector.

#include <iostream>
#include <vector>
using namespace std;
using std::vector;

int main()
{ 
    int number;                //number declared
    while (cin>>number) {      //read the input "number"
    vector<int> number;        //store the input in the vector
    }
    system ("pause");
    return 0;
}


The program compiler successfully. So, I think I succeeded. But as there's no output operation for this one, I'm not sure, if I wrote the program correct. So, I want you C++ experts to review the same & comment if things are correct or it needs some improvement.

Thanks.
You are just declaring a vector called number multiple times. You are not "pushing" values inside it.
instead of :
1
2
3
4
while (cin>>number) {      //read the input "number"
    vector<int> number;        //store the input in the vector
    }
system ("pause");

should be:
1
2
3
4
5
6
7
8
vector<int> myVector; // declare the vector only once
while (cin>>number) {      //read the input "number"
    myVector.push_back( number );        //store the input in the vector
    }
for (int i=0; i<myVector.size(); ++i )
  std::cout << myVector[i] << " ";
std::cout << std::endl;
std::cin.get();


Also, you should avoid system() commands.
Last edited on
technovator, you shouldn't post the same thing twice.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <iterator>
#include <cstdlib>

int main()
{ 
    std::vector<int> v( std::istream_iterator<int>( std::cin ), std::istream_iterator<int>() );

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;

    std::system ("pause");

    return 0;
}
guys, you should notice this:

here's this article:
http://www.cplusplus.com/forum/beginner/104253/


he asked the same question in here:
http://www.cplusplus.com/forum/beginner/104203/

this post is duplicated.
Topic archived. No new replies allowed.