How do I use a vector to store numeric user input?

Basically, I am trying to figure out how I can allow the user to enter an unlimited number of white-space separated numbers, and then once I press enter, each of those numbers will undergo various math operations (eg. sqrt etc.)

But to begin with, my main concern is figuring out how to setup this vector. I just learned about them a couple days ago so I'm fairly new to them.

Wouldn't the vector go something along like this?

1
2
3
4
  vector<int> num;
  int input
  while (cin >> input)
      num.push_back(input);

Thank you for your help!
Last edited on
Wouldn't the vector go something along like this?


Yes, sort of.

I am trying to figure out how I can allow the user to enter an unlimited number of white-space separated numbers, and then once I press enter, each of those numbers will undergo various math operations (eg. sqrt etc.)


But remember the "enter key" is also white-space, as is the "space character" and the "tab character".

Edit: You'll need to tell the loop that your done entering the numbers. The easiest way is to either enter "EOF" after pressing the "enter key" or entering something that will cause the stream to enter a fail state (like entering a non-digit character).






Last edited on
Yep, just a little extra logic to terminate loop when newline comes in from pressing enter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> nums;
    int input;
    
    cout << "Please input space-separated numbers, then press <Enter>: ";
    while (cin && cin.peek() != '\n')
    {
      cin >> input;
      nums.push_back(input);
    }
    
    cout << "\n\nYou've entered: ";
    for(auto& n : nums)
    {
      cout << n << " ";
    }
    cout << endl;
    
    return 0;
}


try it at https://repl.it/repls/BeautifulBlankDesigner
Yep, just a little extra logic to terminate loop when newline comes in from pressing enter.

You're logic is incorrect, you will always get one extra push_back(). You need to read the first item before the loop and the last line of the loop should be the cin >>.

1
2
3
4
5
6
7
8
    cout << "Please input space-separated numbers, then press <Enter>: ";
    cin >> input;

    while (cin && cin.peek() != '\n')
    {
      nums.push_back(input);
      cin >> input;
    }





Could you just take a line of numbers at a time and use stringstream?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
   string line;
   double x;
   vector<double> data;

   cout << "Enter a load of numbers: ";
   getline( cin, line );
   stringstream ss( line );
   while ( ss >> x ) data.push_back( x );

   cout << "Your numbers are:\n";
   for ( double d : data ) cout << d << '\n';
}
Topic archived. No new replies allowed.