I have a set of strings which looks like
"4 7 14 0 2 blablabla"
"3 8 1 40 blablablablabla"
...
The first number N correspond to how many numbers will follow.
Basically, the format of a string is N+1 numbers, separated with a space, followed by an unknown number of irrelevant characters at the end that I don't need.
How can I get all the numbers in variables or a dynamic structure given that I don't know the number N in advance ?
In other words, I'd like something like:
sscanf(s, "%d %d %d %d",&n,&x,&y,&z);
which would work no matter how many numbers in the string.
The first thing would be to break up the input into lines, by using
getline to read it. This will greatly facilitate error recovery and
resynchronization in case of error. It will also facilitate parsing;
it's the strategy which should be adopted almost every time a newline in
the input is significant. After that, you use a std::istringstream to
parse the line. Something like:
std::vector<std::vector<int> > data;
std::string line;
while ( std::getline( input, line ) ) {
std::istringstream l( line );
int iCount;
l >> iCount;
if ( !l || iCount < 0 ) {
// format error: line doesn't start with an int.
} else {
std::vector<int> lineData;
int value;
while ( lineData.size() != iCount && l >> value ) {
lineData.push_back( value ) ;
}
if ( lineData.size() == iCount ) {
data.push_back( lineData );
} else {
// format error: line didn't contain the correct
// number of ints
}
}
}
int input;
std::vector<int> ints;
while(std::cin >> input) //read as long as there is integer
ints.push_back(input);
std::cin.clear(); //clear the error flag
//read the remaining input which most certainly is non-integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With