首页 > 解决方案 > C ++ fstream在while循环中获取函数陷阱

问题描述

为什么这个函数在从文本文件中读取时打印无限点?我找到的唯一解决方案是重新编写 infile 文本并添加一个空行。

void copyText(ifstream& intext, ofstream& outtext, char& ch, int list[]){        
    while (ch != '\n'){ 
        outtext << ch;
        intext.get(ch); 
    }
    outtext << ch; //writes the new line into the text. 
}

标签: c++getfstream

解决方案


如果intext.get(ch);失败(可能因为文件结尾)并且ch不等于'\n'(因为文件的最后一个字符可能不是换行符),则这是一个无限循环。在那种情况下ch永远不会改变并且它不等于'\n'所以你有一个无限循环。

这是正确编写循环的方法。

while (intext.get(ch) && ch != '\n') { 
    outtext << ch;
}

现在 while 循环正在测试读取失败和行尾。


推荐阅读