0

我收到一个文本文档,它是餐厅的菜单。该文件有一份食物清单和价格。该文件是 Ch9_Ex4Data.txt,我需要为客户显示它。我需要使用结构 menuItemType 和 menuItem 类型为 string 和 menuPrice 为 double 类型。我还需要使用该结构的一个数组menuList,一个将数据加载到数组中的函数getData,以及一个显示菜单的函数showMenu。

我的问题是当尝试显示菜单时,我得到的结果甚至与文档本身都不接近。

这是我的代码的一部分(我认为不正确的部分):

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
4

2 回答 2

1

问题就在这里

infile >> menuList[i].menuItem 

只会读取直到它到达空白。所以你第一次阅读

menuLIst[i].menuItem 的值为“Plain”

您应该使用 getline ,默认情况下会读取到行尾

getline(inFile,menuList[i].menuItem);
inFile>>menuLIst[i].menuPrice
inFile.ignore(); //get rid of the carriage return
于 2013-11-13T06:26:05.140 回答
0

我没有你的 sample.txt 但做这样的事情

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 
于 2013-11-13T06:25:47.893 回答