For Loop does only runs once

I am trying to fill out an array by reading data from a txt file. The txt file is in the format: food name
1.99
food name
2.99

I don't understand why my loop in void getData does not reiterate. When I run the program it only works the way I intended for menuList[0], the rest of the indexes have a value of 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream> 
#include <fstream>
using namespace std;

struct menuItemType
{
    string menuItem;
    double menuPrice;
};

void getData(ifstream& infile, menuItemType menuList[]);



int main()
{
    ifstream inFile("Ch9_Ex4Data.txt");
    menuItemType menuList[8];
    getData(inFile, menuList);
    
    
    
    return 0;
}

void getData(ifstream& infile, menuItemType menuList[]){
    
    
     for(int i = 0; i < 8; i++){
         getline(infile, menuList[i].menuItem);
         infile >> menuList[i].menuPrice;
         cout << menuList[i].menuItem << " " << menuList[i].menuPrice;
     }


}
You have to open the file, at least :)

See: http://www.cplusplus.com/doc/tutorial/files/
Beware of the dangers of mixing getline with >>

i=0 getline(infile, menuList[i].menuItem); // reads food name
i=0 infile >> menuList[i].menuPrice; // reads price

i=1 getline(infile, menuList[i].menuItem); // reads the \n at the end of the previous price
i=1 infile >> menuList[i].menuPrice; // sends the stream into error state when it cant interpret the food name as a price.


http://www.cplusplus.com/reference/istream/istream/ignore/
Burn the newline after >> operation.
Last edited on
thank you salem you have solved this for me. I had already tried cin.ignore() and couldn't figure out why that still wasn't working. I had to type infile.ignore() which I didn't realize was legal.
Topic archived. No new replies allowed.