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

时间:2016-08-20 18:34:45

标签: c++

我已读取文件并将其内容存储在字符串中。现在我想查找文件包含多少个唯一单词。

我创建了一个

map< string , int > wordCount;

并创建了一个函数,将文件内容放在字符串中并将其添加到地图

  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()。为什么会发生这样的事情?我找不到合理的答案。感谢

1 个答案:

答案 0 :(得分:1)

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

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'进行比较将永远不会有效,无论它应该完成什么。

相关问题