gpt4 book ai didi

c++ - 字符串迭代器找不到 end()

转载 作者:行者123 更新时间:2023-11-30 05:23:35 25 4
gpt4 key购买 nike

我已经读取文件并将其内容存储在一个字符串中。现在我想找出该文件包含多少个独特的单词。

我创建了一个

map< string , int > wordCount;

并创建了一个函数,将文件的内容放入字符串中并将其添加到 map

  void wordCounter(){
string content;
file.seekg( 0, ios::end );
content.resize( file.tellg());
file.seekg( 0, ios::beg);
file.read( &content[0] , content.size());
ostringstream os;
for( string::iterator current , next = content.begin() ; current != content.end() || next != content.end();){
if( *next == ' ' || *next == '\r\n'){
wordCount[ os.str() ]++;

while( next != content.begin() && (*next == ' ' || *next ==' \r\n')){
next++;
}
os.str(" ");
current = next;
}else{
if( *next <= 'Z' && *next >='A')
os << char( *next - ('Z'-'z'));
else
os << (*next);
next++;
}
}
}

但这会导致死循环。 itrator 似乎找不到字符串的 end()。为什么会发生这样的事情?我找不到合理的答案。谢谢

最佳答案

显示的代码中存在多个错误。

for( string::iterator current , next = content.begin() ;
current != content.end() || next != content.end();)

这声明了 currentnextnext 被初始化为 content.begin()current 未初始化,然后与值进行比较。这是未定义的行为。

if( *next == ' ' || *next == '\r\n'){

*next 是一个字符,单个字符。将单个字符与两个字符进行比较,'\r\n',无论应该完成什么,都不会起作用。

关于c++ - 字符串迭代器找不到 end(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com