这个问题困扰了我一个晚上,谢谢!
此代码将文件中的最后一行写入两次。为什么?
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int strSize = 1000;
int main(int argc,char *argv[])
{
ifstream infile(argv[1]);
if(!infile) cerr<<"infile error!"<<endl;
ofstream outfile(argv[2]);
int sequenceNum = 1;
char str[strSize];
while(infile){
infile.getline(str,strSize);
if(sequenceNum>469)
str[0] = '2';
else if(sequenceNum>67)
str[0] = '4';
else if(sequenceNum>1)
str[0] = '1';
else
str[0] = '3';
outfile<<str<<endl;
++sequenceNum;
}
return 0;
}
在infile.getline(str,strSize);
之后,str
为NULL
,如果不修改str,为什么为null?但在 if(sequenceNum>469)
之后,str
成为最后一行。
这段代码只写最后一行一次。
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int strSize = 1000;
int main(int argc,char *argv[])
{
ifstream infile(argv[1]);
if(!infile) cerr<<"infile error!"<<endl;
ofstream outfile(argv[2]);
int sequenceNum = 1;
char str[strSize];
while(infile){
infile.getline(str,strSize);
if(strlen(str) != 0){//The key is this sentence.
if(sequenceNum>469)
str[0] = '2';
else if(sequenceNum>67)
str[0] = '4';
else if(sequenceNum>1)
str[0] = '1';
else
str[0] = '3';
outfile<<str<<endl;
++sequenceNum;
}
}
return 0;
}
最佳答案
问题是当 infile.getline
读取最后一行时(即读取到 EOF),while(infile)
仍将计算为真,从而导致循环再次运行。但是,由于 infile
读取了整个文件,infile.getline
将失败,并且 str
将变为空字符串。但是,由于您的原始代码覆盖了第一个字符,它摆脱了空终止符,因此它最终重用了上次的内容。
相反,你想要这样的东西:
while (infile.getline(str, strSize)) {
if (sequenceNum>469)
...
}
关于C++ getline() 和文件 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971593/