简体   繁体   中英

Not getting the right output reading a file in c++

I'm helping a friend with a simple c++ task about reading a file and printing it, here is the code:

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

using namespace std;
const int P=10;
struct persona
{
    string nombre;
    int puntos;
};
typedef persona vec[P];


int main (void)
{

    ifstream f;
    vec v;
    int i;

    f.open("estadisticas2.txt");
    if(!f)
    cout<<"Error abriendo fichero\n";
    else
    {
        for(i=0;i<P;i++)
        {  
            getline(f,v[i].nombre);
            f >> v[i].puntos;
            f.ignore(); 

        } 
         f.close(); 
        for(i=0;i<P;i++)
         {
            cout<<v[i].nombre<<"\n";
            cout<<v[i].puntos<<"\n";
        }

    }
    system("pause");
    return 0;
}      

I checked if it was problem about not reading or the for loop not going the right times. Also initialized the vector v, but I only get this output:

unknown 
0
pene
20
ojete
40
tulia
240

0

1875655176

0

16

-1

1875658144

Insted of (the real .txt value):

unknown 
0
pene
20
ojete
40
tulia
240 
Ano 
2134
lolwut
123
unknown 
0 
unknown 
0 
unknown 
0 
unknown 
0                                                                                                                                                                                                                            

Thanks for everything!

Your f.ignore() accounts for discarding one char, which you assume is the newline, But in your input file:

unknown 
0
pene
20
ojete
40
tulia
240 <=== here
Ano 
2134
lolwut
123
unknown 
0 <=== here
unknown 
0 <=== here
unknown 
0 <=== here
unknown 
0 <=== here

All places marked above have a trailing space and a trailing newline. To consume everything after your number extraction you should use:

f.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

which will discard everything in the input stream up-to-and-including the next newline, thereby eating the space and keeping your line-relative position intact.

As a side note, you should also be checking your IO operations for both getline and the numeric extraction.

{
  getline(f, v[i].nombre);
  string l;
  getline(f, l);
  v[i].puntos = stoi(l);
}

Don't know why your example doesn't work, but I don't like mixing getline with >> .
Also you forgot to include string

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