我有此代码:
//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;
}
我收到此警告:
隐式转换失去整数精度
答案 0 :(得分:1)
所有处理大小和索引的std::string
方法都对std::string::size_type
值而不是int
值进行操作。 size_type
通常是std::size_t
,它是一个 unsigned 整数。将无符号整数转换为有符号整数可能会失去精度。
因此,startingPosition
,endingPosition
和delimiterLength
必须声明为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;
}