从getline()获取的字符串长度
Length of a string which is got from 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
为字典文件,如"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. " ")
这将忽略任何尾随空格
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取