c++ - 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.
}
解决方案
如果intext.get(ch);
失败(可能因为文件结尾)并且ch
不等于'\n'
(因为文件的最后一个字符可能不是换行符),则这是一个无限循环。在那种情况下ch
永远不会改变并且它不等于'\n'
所以你有一个无限循环。
这是正确编写循环的方法。
while (intext.get(ch) && ch != '\n') {
outtext << ch;
}
现在 while 循环正在测试读取失败和行尾。
推荐阅读
- sharepoint-list - 添加标准文本/语句列表以在电源应用程序的描述框(文本输入控件)中选择和添加,以允许用户在表单中少输入
- android - 如何向单例类中的列表添加值?(扑)
- flutter - E/AndroidRuntime(14021):致命异常:grpc-default-executor-0
- google-chrome - 通过脚本命名的 chrome 窗口
- reactjs - vscode jest 断点未在主编辑器中打开
- for-loop - 如何在 for 循环中等待所有生成的 JoinHandles
- javascript - NodeJs如何实现http包的listen()函数?
- javascript - 在桌面上显示平板电脑/移动版的某些区域,反之在 WordPress 中显示
- authentication - 用于公共 SaaS 产品的 Active Directory (AD)?
- java - 将 postgres bytea 与字符串进行比较时,Spring JDBC 抛出异常