简体   繁体   中英

getline() not reading first lines

I am c++ beginner and this is for school..

I am trying to read a file about 28kb big. The program works but it doesnt print the first 41 lines. It works fine with a smaller file. At first i was reading into a char array and switch it to strings. i also tried changing the log buffer but it apparently it should be big enough.. I feel like this should be very simple, but just cant figure it out..

Any help will be greatly apreciated.. Thanks!

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cerrno>

using namespace std;

struct espion
{
    char nom[30];
    char pays[20];
    char emploi[29];

};


int main()
{
    const int MAX_NOM = 30, MAX_PAYS = 20, MAX_EMPLOI = 29;
    char nomFichier[50] = "espion.txt";



    ifstream aLire;
    aLire.open(nomFichier, ios::in|ios::binary);

    if(!aLire.is_open()){
        exit(EXIT_FAILURE);
    }


    std::string infoEspion;


    while(aLire)
    {
        infoEspion.clear();
        std::getline(aLire, infoEspion);
        cout << infoEspion ;

    }

    aLire.close();


    system("pause");
    return 0;

}

From the system("pause"), it looks like you're running on Windows. With ios::binary, the end-of-line marker is not translated, and the cout << infoEspion; statement prints these "raw" lines in such a way that all of the lines are written on top of each other. (More specifically, each line will end with a return but no newline, so the cursor goes back to the start of the same line after executing each cout statement.) If you take out the ios::binary, you will echo all of the input on a single, very long line. Changing the statement to cout << infoEspion << endl; will echo all of the lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM