【问题标题】:displaying a text file显示一个文本文件
【发布时间】:2013-11-13 06:16:21
【问题描述】:

我收到一个文本文档,它是餐厅的菜单。该文件有一份食物清单和价格。该文件是 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

【问题讨论】:

  • 请展示您的示例文件内容

标签: c++ arrays struct ifstream


【解决方案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

【讨论】:

    【解决方案2】:

    我没有你的 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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      相关资源
      最近更新 更多