警告隐式转换会失去整数精度

时间:2019-03-09 18:32:33

标签: c++

我有此代码:

//getIndividualWords(..) basically splits a sentence based on a specified delimiter: here delimiter is SPACE

vector<string> getIndividualWords(string line, string delimiter)
{
    int startingPosition = 0, endingPosition = 0, delimiterLength = delimiter.length();

    string words;
    vector<string> wordList; //stores all the words received by splitting the sentence

    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos) //the loop continues till it finds SPACES in the sentence
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }

    wordList.push_back (line.substr (startingPosition)); //inserts the words into a vector container
    return wordList;
}

我收到此警告:

  

隐式转换失去整数精度

1 个答案:

答案 0 :(得分:1)

所有处理大小和索引的std::string方法都对std::string::size_type值而不是int值进行操作。 size_type通常是std::size_t,它是一个 unsigned 整数。将无符号整数转换为有符号整数可能会失去精度。

因此,startingPositionendingPositiondelimiterLength必须声明为std::string::size_type,以匹配std::string实际使用的内容。

尝试一下:

vector<string> getIndividualWords(const string &line, const string &delimiter)
{
    string::size_type startingPosition = 0, endingPosition, delimiterLength = delimiter.length();
    string words;
    vector<string> wordList;

    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos)
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }

    if (startingPosition < line.length())
        wordList.push_back (line.substr (startingPosition));

    return wordList;
}