Link to home
Start Free TrialLog in
Avatar of ugeb
ugebFlag for United States of America

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:

Jesse 18 50 48 97 76 34 98
The 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;

Open in new window

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?
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

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.
Avatar of ugeb

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
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ugeb

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'.
>> I think you intended to use  'piecemeal' instead of 'peace-mill'.
Heh. Yes, you are right. My bad :)