Reading unkown number of elements in a line

Hello!

I am uncertain how to do the following. If we have an unknown number of elements in a line how can I read them? All of elements would be of the same type.

To clarify because I don't know how good my English is:
I could get this kind of input:
1 2 3 4 5 6 7 8 9 10


Or this kind:
1 2 3


I know how to read them if we have determined number of elements, but I can't find out how to do it with unknown number.

Thank you.

S.
Use string streams:

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
26
27
#include <sstream> //important library
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    ifstream fin("input.txt");
    string Line;
    stringstream iss; //declare the stream
    int num; //This will hold the data, it could be an array if you like.  It can be whatever type you need.

    while (getline(fin, Line))  // Put each line into variable "Line"
    {
        iss << Line; // Put the line into a string stream;

        while (iss.good()) // while the stream is not empty
        {
            iss >> num; //get data from the stream. This will give you only up until the next whitespace.
                        //Get numbers, strings, whatever you want.

            cout << num << " ";
        }
    }

    return 0;
}
Last edited on
This would work if entering data trough console not from file? If replace fin with cin in getline function, and I get data with cin?

S.
Last edited on
Topic archived. No new replies allowed.