C++解析,从字符串中获取可变数量的整数

Jou*_*cks 2 c++ string parsing

我有一组看起来像
"4 7 14 0 2 blablabla"
"3 8 1 40 blablablablabla" 的字符串
......

第一个数字N对应于将跟随多少个数字.
基本上,字符串的格式是N + 1个数字,用空格分隔,后面跟着我不需要的未知数量的无关字符.

考虑到我事先不知道数字N,我怎样才能得到变量或动态结构中的所有数字?

换句话说,我想要像:

sscanf(s, "%d %d %d %d",&n,&x,&y,&z);
Run Code Online (Sandbox Code Playgroud)

无论字符串中有多少个数字都可以使用.

Jam*_*nze 6

第一件事就是通过使用getline它来将输入分解成行 .这将极大地促进错误恢复和重新同步,以防出现错误.它还有助于解析; 这是几乎每次输入中的换行都很重要时应该采用的策略.之后,使用a std::istringstream来解析该行.就像是:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)