Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ parse, fetch a variable number of integers from a string

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.

like image 690
Joucks Avatar asked Jan 28 '26 06:01

Joucks


2 Answers

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
        }
    }
}
like image 156
James Kanze Avatar answered Jan 30 '26 22:01

James Kanze


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
like image 34
Nawaz Avatar answered Jan 30 '26 21:01

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!