Question about reading input

In a program i'm writing i'm supposed to read user input on one line and the user will have a max of 6 things on the line. I've been trying to figure out how to read in this unknown number of things. Ideally I want all of these stored in an array. I tried using cin and using an array like this:
cin >>array[0]>>array[1]>>array[2]>>array[3]>>array[4]>>array[5];

This however will not allow them to skip any of the array. I have the rest of the program written but this is the last part I need.

Examples of user usage:
1. Enter command and all arguments: wc
2. Enter command and all arguments: wc -l
3. Enter command and all arguments: grep -i file.*
etc...
Last edited on
Hello:

I would take the full line written by the user with std::getline(std::cin,stdstringnamewheretosave);

Then, adapt this from stack overflow to divide your std::string into parts, this will loop with each word written delimited by a space, you can break the loop after 6 words have been processed:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
#include <sstream>

std::string myText("some-text-to-tokenize");
std::istringstream iss(myText);
std::string token;
while(getline(iss, token, '-'))
{
      std::cout << token << std::endl;
}
A variation on the getline, stringsteam idea. Uses a vector to store each part.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    vector<string> arr;
    string line;
    getline(cin, line);
    string word;
    istringstream ss(line);
    while (ss >> word)
    {
        arr.push_back(word);
    }
    
    cout << "Number of words: " << arr.size() << endl;
    for (size_t i=0; i<arr.size(); i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}
Topic archived. No new replies allowed.