Frage

I am given a text document that is a menu of a restaurant. The document has a list of food and the prices. The file is Ch9_Ex4Data.txt and I need to display it for the customer. I need to use a struct menuItemType with menuItem of type string and menuPrice of type double. I also need to use an array, menuList, of the struct, a function getData that loads the data into an array, and a function showMenu that shows the menu.

My issue is when trying to display the menu I get different results that are not even close to the document itself.

Here is part of my code(The part that I think is incorrect):

struct menuItemType
{
    string menuItem;
    double menuPrice;
};


void welcome()
{
    menuItemType menuList[8];

    char ready;
    int millisecond = 1000;

    ifstream infile;

    infile.open("Ch9_Ex4Data.txt");

    getData(infile, menuList);

        ...

    showMenu(menuList);

        ...
}

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

    for(i= 0; i < 8; i++)
    {
        infile >> menuList[i].menuItem >> menuList[i].menuPrice;
    }
}

void showMenu(menuItemType menuList[])
{
    int i;

    for(i = 0; i < 8; i++)
    {
        cout << menuList[i].menuItem << endl;
        cout << menuList[i].menuPrice << endl;
    }
}




  text file:



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
War es hilfreich?

Lösung

Problem is here

infile >> menuList[i].menuItem 

will only read until it reaches white space. so the first time you read in

menuLIst[i].menuItem has the value of "Plain"

you should be using getline which by default reads until the end of the line

getline(inFile,menuList[i].menuItem);
inFile>>menuLIst[i].menuPrice
inFile.ignore(); //get rid of the carriage return

Andere Tipps

I dont have your sample.txt but do something like this

pFile = fopen ( "sample.txt" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
//now you have all the data of the file in a string buffer(array)
do operations on it 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top