ugeb
asked on
How to read a c++ line with strings and variable numbers of elements
I have a line of console input that can contain both strings and integers, but I don't know how many. I do know whether the variable arguments will be strings or numbers. A typical line is:
This format is a string, followed by a specific integer, followed by a variable number of strings. I know I can do this (assuming I have no more than 100 integers]:
Jesse 18 50 48 97 76 34 98The format is a string followed by a specific integer followed by a variable number of integers. Another format could be:
Jesse 18 this line contains strings of varying number
This format is a string, followed by a specific integer, followed by a variable number of strings. I know I can do this (assuming I have no more than 100 integers]:
string name;
int age, values[100];
cin >> name >> age;
But how do I read in the rest of the array since I don't know how many integers are there? I tried a while loop checking for EOF, but it picked up nothing. What's the right way to do this?
You are always better off reading in the whole line (using getline into a std::string) and then parsing out the line. Trying to read a line peace-mill will always be problematic. You can use a std::vector<int> to store your int values as you parse them out.
ASKER
I don't know what "peace-mill" means, but the issue would still be how do I get the array out of the line? I'm not worried about vector vs. array, just getting the values from the string (whether console input or a string in memory) into the array.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Yes, that solution works for me, thanks.
@evilrix, if you mean 'bit by bit', I think you intended to use 'piecemeal' instead of 'peace-mill'.
@evilrix, if you mean 'bit by bit', I think you intended to use 'piecemeal' instead of 'peace-mill'.
>> I think you intended to use 'piecemeal' instead of 'peace-mill'.
Heh. Yes, you are right. My bad :)
Heh. Yes, you are right. My bad :)