Help with fstream into an array of structs

Hello,

I've been working on a program to collect data from a txt file into an array of structs. I think that I can figure out how to fill the array of structs however, I'm having trouble capturing the appropriate information into each member.

My function is not pulling all of the appropriate data. the number initial int is only reading the 3 not the proceeding 2 0s, the first string is ok, the 2nd string was ok until I messed with the ignore(); the third string only captures seed and not pokemon. The next two doubles capture 0 instead of what is in the txt file. and the ablities are not captured.

txt file:
003
venusaur
Grass
Seed Pokemon
6.7
220.5
Overgrow
-


main.cpp:

void getfile()
{
cout << "getting data...";
ifstream inputFile;
inputFile.open("pokedex.txt");
string space;
inputFile >> poke[counter].natnum;
inputFile >> poke[counter].name;
inputFile.ignore(256,' ');
getline (inputFile, poke[counter].type);
inputFile >> poke[counter].specie;
inputFile >> poke[counter].height;
inputFile >> poke[counter].weight;
inputFile.ignore();
getline (inputFile, poke[counter].ability1);
getline (inputFile, poke[counter].ability2);
inputFile >> space;
counter ++;
inputFile.close();


cout << "Return to main menu?";
}



Since getline(...) shouldn't read the new line of the previous line (>> doesn't remove the new line) you want to ignore the new line character not space.

change

inputFile.ignore(256,' ');

to

1
2
inputFile.ignore(256,'\n');
 // Even better: std::numeric_limits<std::streamsize>::max() instead of 256 



This applies to all transitions from >> to getline(...).
the number initial int is only reading the 3 not the proceeding 2 0s

That is not an input problem, if the value is really an integer. It is simply a matter of how the value is displayed later.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{    
    int n = 3;
    cout << "n = " << n << '\n';

    cout << setfill('0');    
    cout << "n = " << setw(3) << n << '\n';
}
n = 3
n = 003


Alternatively, just treat the value as a string rather than an int.
Topic archived. No new replies allowed.