Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ getline() and file EOF

Tags:

c++

This problem has troubled me for a night.Thanks!

This code will write the last line in file twice.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;
}

After infile.getline(str,strSize); the str is NULL, if str is not modified,why is null? but after if(sequenceNum>469), the str become the last line.

This code just write the last line only once.

#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;
}
like image 637
Aleeee Avatar asked Dec 20 '22 02:12

Aleeee


1 Answers

The problem is when infile.getline reads the last line (i.e. it reads until EOF), while(infile) will still evaluate to true, causing the loop to be run again. However, since infile has read the entire file, infile.getline will fail, and str will become an empty string. However, since your original code overwrites the first character, it gets rid of the null terminator, so it winds up reusing the contents from last time.

Instead, you want something like:

while (infile.getline(str, strSize)) {
    if (sequenceNum>469)
    ...
}
like image 71
Drew McGowen Avatar answered Dec 24 '22 01:12

Drew McGowen