Reputation: 33
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!
Upvotes: 1
Views: 113
Reputation: 66234
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.
Upvotes: 1
Reputation: 75755
{
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
Upvotes: 0