0

レストランのメニューであるテキスト ドキュメントが渡されます。ドキュメントには、食品と価格のリストがあります。ファイルは Ch9_Ex4Data.txt で、お客様に表示する必要があります。string 型の menuItem と double 型の menuPrice を持つ構造体 menuItemType を使用する必要があります。また、構造体の配列 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 の値は「プレーン」です

デフォルトで行末まで読み取る 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 に答える