Reputation: 65
I'm currently trying to load data from a text into a vector of structs. It works for the first line, then dies and prints out zeros and the reason is unbeknownst to me.
My code is below and it is quite simple, as well as the text file from which I'm reading. I'd appreciate some help as I can't figure out why its doing this.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <string>
using namespace std;
struct Symbol
{
int type;
string name;
};
int main()
{
/************ VARS ***************/
string line;
int line_count;
int increment;
/************ Vector of Symbols ***************/
vector<Symbol> symbols;
cout << "Opening file..." << endl;
ifstream file;
file.open("symbols.txt");
if(!file)
{
cout << "System failed to open file.";
}
while(file)
{
Symbol temp;
getline(file, temp.name);
file >> temp.type;
symbols.push_back(temp);
increment++;
}
//Just to test and see if its loading it correctly...
for(int i = 0; i < symbols.size(); i++)
{
cout << symbols[i].name << endl;
cout << symbols[i].type << endl;
}
}
Input File:
count
2
num
2
myFloat
4
myDouble
5
name
6
address
6
salary
5
gpa
4
gdp
5
pi
5
city
6
state
6
county
6
ch
0
ch2
0
ID
1
studentID
1
max
3
max2
3
greeting
6
debt
5
age
2
Output:
Opening file...
count
2
0
Upvotes: 0
Views: 221
Reputation: 96855
The loop that you're using is not taking into account the fact that the last formatted extraction left a newline in the stream. When std::getline()
runs the second time, it will find the newline and stop extrating characters (thus nothing is inserted into temp.name
. The stream sets std::ios_base::failbit
into its stream state and any further attempts at performing input fail.
The newline has to be cleared. You can do this using std::ws
. Also, you can restructure your loop as follows:
for (Symbol temp;
std::getline(file >> std::ws, temp.name) && file >> file.type; )
{
symbols.push_back(temp);
increment++;
}
Upon further look I notice that you don't even need std::getline()
for this. Just extract using operator>>()
:
for (Symbol temp; file >> temp.name >> temp.type; )
{
symbols.push_back(temp);
increment++;
}
Upvotes: 1