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

Length of a string which is got from getline()

本文关键字:字符串 获取 getline      更新时间:2023-10-16

我有以下代码:

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为字典文件,如"dict.txt"。在"dict.txt"中是这样的:

aa
aah
aahed
aahing
aahs
...
如上所示,其中只有许多单词。假设letters是13。所以我认为密码应该打印有13个字母的单词,比如abacterialope。但实际上它打印的单词有12个字母,而word.size()是13个字母。

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

如果所有的单词都是用空格(空格,制表符,换行符,回车符等)分隔的,那么你可以通过一个函数调用将整个文件放入vector中:

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

引用:

  • std::copy
  • std::istream_iterator
  • std::back_inserter

如果要删除所有不超过13个字符的单词,可以执行

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

引用:

  • std::remove_if
  • Lambda表达式

尝试使用:

getline(file, word. " ")

这将忽略任何尾随空格