aveleon
aveleon

Reputation: 167

C++ ifstream skips 1st line

Here is my code.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main ( ){
    ifstream inFile;

    char date1[8], date2[8];
    int dayTemp1[24], dayTemp2[24];

    inFile.open("weatherdata.txt");
        if(inFile.fail()){
        cout << "File failed to open.";
        exit(1);
    }

    inFile >> date1 >> date2;


    cout << date1 << endl;
    cout << date2 << endl;

inFile.close();

return 0;
}

The first two lines of the weatherdata.txt file are:
01/04/13
01/05/13


date1 is supposed to contain the first date but when printed it only prints the '\n' character (an empty line). I don't know what is going on with the code as to why it is skipping the first date line. Any and all help is appreciated. I'm a beginner to C++.

Upvotes: 2

Views: 1062

Answers (2)

David G
David G

Reputation: 96855

@billz gave you a solution to the problem, so I'll provide an explanation:

The problem was that your char arrays allocated exactly 8 bytes (or characters in this case) but did not leave room for the obligatory null byte (\0). My assumption is that's causing undefined behavior, and when you print you're not getting the correct output because of this. For example, on Linux I'm not getting the first line as blank, I actually get:

01/04/1301/05/13
01/05/13

This was a clear indicator to me the the insertion did not stop when it reached the presumed null byte. The solution is to allow your char arrays hold at least 9 bytes.

Using std::string is beneficial in this context as it avoids this problem completely (it is a container of a dynamically-sized string). Its size will accompany the extra characters (as well as the null byte).

Upvotes: 0

billz
billz

Reputation: 45470

use std::string instead:

#include <string>
std::string date1;
std::string date2;
//...

inFile >> date1 >> date2;

OR

std::getline(inFile, date1);
std::getline(inFile, date2);

Upvotes: 1

Related Questions