Reputation: 3
Having trouble reading information from a text file to parallel arrays. The info is arranged as such in the file:
Name
Street Address
City, State, Zip
Order size
Name
Street Address
City, State, Zip
Order size
Basically I need to pull the names, street address, and city/state/zip as lines into string arrays and then pull the order size into an int array to do some calculations. Grand total of 4 arrays.
Problem is it'll read the first order just fine, but the second order appears different that the input and all orders after that just show as numbers:
John Doe
123 Main Street
City, State Zipcode
John Doe
123
Main Street
City, State Zipcode
9
0
9
9
4679937
9
0
9
9
4710208
And here's the relevant code:
const int ORDERS = 10;
cout << "Reading from file..." << endl;
ifstream inputFile;
string name[ORDERS], streetAddress[ORDERS], cityStateZip[ORDERS];
string line;
int orderSize[ORDERS];
inputFile.open("Orders.txt");
for(int i = 0; i < ORDERS; i++)
{
getline(inputFile, line);
name[i] = line;
getline(inputFile, line);
streetAddress[i] = line;
getline(inputFile, line);
cityStateZip[i] = line;
inputFile >> orderSize[i];
}
inputFile.close();
for(int i = 0; i < ORDERS; i++)
{
cout << name [i] << endl;
cout << streetAddress[i] << endl;
cout << cityStateZip[i] << endl;
cout << orderSize [i] << endl;
}
Any ideas? Seems like it's trying to read the strings as ints after the first order or something.
Upvotes: 0
Views: 5377
Reputation: 72215
The >> extraction operator leaves the trailing \n of the line in the input stream. The next getline thus will not read the line you want, but instead just the trailing \n of the order line. Either use getline exclusively and extract the int from the line after the fact, or make sure that you skip the rest of the line after the extraction.
In addition, what Ben Voigt and john said.
Upvotes: 1