Search code examples
c++arraysloopsifstream

Function with getline giving extra output


So i have this function out of one of my programs, and before it was giving me all of these(-9.25596e+061) and only the first line. But then i put { ',' } in my getline and got it to print whole file but still got the numbers(which is a memory dump right?)

void getMenuFromFile(ifstream& inFile, menuItemType menu[], int menuSize) {
    for (int i = 0; i < menuSize; i++) {
        getline(inFile, menu[i].menuType, ',');
        inFile >> menu[i].menuPrice;
        inFile.ignore();
    }
}

Input:

Plain Egg            $1.45
Bacon and Egg        $2.45
Muffin               $0.99
French Toast         $1.99
Fruit Basket         $2.49
Cereal               $0.69
Coffee               $0.50
Tea                  $0.75

Output:

Plain Egg            $1.45
Bacon and Egg        $2.45
Muffin               $0.99
French Toast         $1.99
Fruit Basket         $2.49
Cereal               $0.69
Coffee               $0.50
Tea                  $0.75
-9.25596e+061

-9.25596e+061

-9.25596e+061

-9.25596e+061

-9.25596e+061

-9.25596e+061

-9.25596e+061

-9.25596e+061
Press any key to continue . . .

Solution

  • Your code has a number of problems:

    • You are telling std::getline to stop at ',' but your input does not contain any. Hence, it consumes the entire file the first time it is called. Eventually, you've meant to use a '$' instead?

    • After that, the attempt to extract the price and all the other lines fails. You would have noticed if you would check the state of the stream as in

      if (!inFile) { cerr << "damn it!\n"; }
      
    • Even if that problems were fixed, you would still fail to store 1.45 and all the other prices in an int. Maybe you wanted a float instead?

    Your output comes this way:

    First, you see the entire contents of the file that went into menu[0].menuType. For all the remaining entries, you get an empty (default constructed) string and random garbage values that happened to be in memory for the prices (as ints are not value-initialized).

    Update: After reviewing your output, I doubt that menuItemType::menuPrice is an int as you've said in your comment. Isn't it already a float or double? The other problems mentioned above still remain.