这个问题困扰了我一个晚上。谢谢!
此代码将两次写入文件中的最后一行。为什么?
#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;
}
在is之后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;
}