0

下面的这个函数简单地接受一个用 64 位整数填充的字符串,每个值由一个分隔符分隔,它将被放入向量中。

vector<unsigned long long int> getAllNumbersInString(string line, char delim){
    vector<unsigned long long int> v;

    string word;
    stringstream stream(line);
    unsigned long long int num;

    while(getline(stream, word, delim))
        num = atol(word.c_str());
        v.push_back(num);
    }

    return v;
}

例如,当我们将 ',' 作为分隔符时,此函数可以正常工作,但是,如果字符串变量“line”中的数据如下所示,则分隔符将失败:

     432   12332    2234   12399   

虽然数据似乎使用空格作为分隔符,但使用上面的代码,整个代码将在逻辑上失败。例如,空白之间的空白是未定义的,atol 将返回 0,并将这些零放入向量中。

为了更好地防范这些异常,我应该在这段代码中采取哪些措施?

4

2 回答 2

3

Is there some reason you can't/won't just use something like this?:

while (stream >> num)
   v.push_back(num);

or just:

vector<unsigned long long int> getAllNumbersInString(string line) { 
    istringstream stream(line);  
    typedef unsigned long long int T;

    vector<T> v((istream_iterator<T>(stream)), istream_iterator<T>());
    return v;
}

If you have to deal with delimiters other than whitespace, you can create a ctype facet to specify what else should be treated as delimiters.

于 2013-02-10T17:45:24.880 回答
1

You can let the iostreams library take care of whitespace for you:

unsigned long long int num;
while(stream >> num)
    v.push_back(num);
于 2013-02-10T17:44:32.960 回答