-1

When trying to read data from a file, I don't know why but it reads me from the second line. I need to read the first data separated by a space and it actually reads as I want. But it skips the first line and writes the last line twice. Below is what is in the file and the code.

What is in txt file:

H Budapeszt 8 10 11 
I Neapol 8 12 5 
F Marsylia 5 6 6
GB Leeds 8 7 4
D Frankfurt 10 7 8
I Genua 4 6 8
D Dortmund 11 12 7
NL Rotterdam 8 12 9
D Dusseldorf 9 9 12
DK Kopenhaga 4 7 10

Code:

#include <fstream>
#include <iostream>

using namespace std;

int main() {
    string a;
    string linia;
    fstream plik;
    plik.open("galerie_przyklad.txt",ios::in);

    if(plik.good()==false){
        cout << "Nie udalo sie otworzyc pliku!" << endl;
        exit(0);
    }
    else{
        while(getline(plik, linia)){
            plik >> a;
            cout <<  a << endl;
        }
    plik.close();
    }
    return 0;

Result in terminal:

I  
F 
GB 
D 
I 
D 
NL 
D 
DK
DK
  • 1
    You can use a `std::stringstream` to tokenize the line once you've read it, but you could also just read each token one by one with `>>` from the file and skip `getline` completely. – Retired Ninja May 17 '21 at 16:37
  • @user4581301 that's a bad dupe target. The issue here is a mix of `std::getline` and the extraction operator (`>>`) on the stream. – scohe001 May 17 '21 at 16:37
  • Option 2 of the first answer in the duplicate should get you on the right path. – user4581301 May 17 '21 at 16:37
  • Disagree @scohe001 It shows how to mix `getline` and the extraction operator for this task – user4581301 May 17 '21 at 16:38
  • So where is the error in my code? Or what's is the best solution for my problem? – SzczeryJerry May 17 '21 at 17:14
  • You have 2 bugs. One is you read the whole line then ignore it and read an additional integer. The second is related to this: [https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) the answer of linked duplicate should fix both problems. – drescherjm May 17 '21 at 17:37

0 Answers0