這個問題困擾了我一個晚上。謝謝!C++ getline()和文件EOF
這段代碼會將最後一行寫入文件中兩次.WHY?
#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沒有被修改,爲什麼是空?但在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;
}