C++ C++;fstream在while循环中获取函数陷阱
为什么这个函数在读取文本文件时打印无限多个点? 我找到的唯一解决方案是重写内嵌文本并添加一条空行C++ C++;fstream在while循环中获取函数陷阱,c++,get,fstream,C++,Get,Fstream,为什么这个函数在读取文本文件时打印无限多个点? 我找到的唯一解决方案是重写内嵌文本并添加一条空行 void copyText(ifstream& intext, ofstream& outtext, char& ch, int list[]){ while (ch != '\n'){ outtext << ch; intext.get(ch); } outtext << c
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.
}
void copyText(ifstream&intext、ofstream&outtext、char&ch、int list[]){
而(ch!='\n'){
outtext如果intext.get(ch);
失败(可能是因为文件结尾),并且ch
不等于'\n'
(因为文件的最后一个字符可能不是换行符),则是一个无限循环。在这种情况下,ch
将永远不会更改,并且它不等于'\n'
,因此您有一个无限循环
下面是如何正确编写循环
while (intext.get(ch) && ch != '\n') {
outtext << ch;
}
while(intext.get(ch)&&ch!='\n'){
outtext如果在无限循环中运行,则表示文件中没有“\n”字符(这就是原因,您可以通过添加空行来停止无限循环)。如果您正在查找文件结束检查,请将while loop check更改为ch!=0