从getline()获取的字符串的长度

时间:2014-05-24 17:16:01

标签: c++ string getline

我有以下代码:

ifstream file(filename);
for(string word; getline(file, word);){
    if(word.size() == letters){
        cout << "word: " << word << endl;
        cout << "size: " << word.size() << endl;
        dict.push_back(word);
    }
}

在代码中,filename是一个双重文件,如&#34; dict.txt&#34;。在&#34; dict.txt&#34;是这样的:

aa
aah
aahed
aahing
aahs
...

如上所示,其中只有很多单词。假设letters是13.所以我认为代码应该打印有13个字母的单词,比如abacterialope。但实际上它会打印出包含12个字母的单词,而word.size()则为13。

那么,为什么会发生这种情况呢?在我的记忆中,size()应该打印string中的字符数。

2 个答案:

答案 0 :(得分:0)

尝试使用:

getline(file, word. " ")

这将忽略任何尾随空格。

答案 1 :(得分:0)

如果所有单词都是空格(空格,制表符,换行符,回车符等),则可以在单个函数调用中将整个文件放入向量中:

std::copy(std::istream_iterator<std::string>(file),
          std::istream_iterator<std::string>(),
          std::back_inserter(dict));

参考文献:


如果您想要删除所有不是13个字符的单词,您可以

dict.erase(std::remove_if(std::begin(dict), std::end(dict),
                          [](const std::string& s) { return s.length() != 13) });

参考文献: