1

目標は、プログラムがテキスト ファイルから読み取られ、# 記号で解析され、アイテムと価格が出力されることです。3 つのアイテムがあるため、ループしているため、繰り返す必要があります。また、アイテムの量を (行に基づいて) カウントし、すべての価格を合計して合計価格を計算する必要もあります。解析する必要があるテキスト ファイルは次のようになります。

ハンマー#9.95
のこぎり#20.15
シャベル#35.40

私のコードは次のとおりです。

#include <string> 
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
ifstream invoice("invoice2.txt");
string name;
int count = 0;
int totalPrice = 0;
float price = 0.0;
while(invoice.open())
{
    getline(file, line);
    ++count;
    for (string line; getline(file, line); )
    {
        size_t sharp = line.find('#');  
        if (sharp != string::npos)
        {

                string name(line, 0, sharp);
                line.erase(0, sharp+1);
                price = stof(line);
            cout << "*** Invoice ***\n";
            cout << "----------------------------\n";
                cout << name << "               $" << price << "\n\n";
            cout << "----------------------------\n";
            cout << count << " items:             " << totalPrice;
            }
    }
}
return 0;
}

テキストファイルが終了するまでループを繰り返す必要があり、その後中断して合計価格を出力する必要があります

4

2 に答える 2

1

まず、なぜwhileループなのですか?あなたはそれを必要としません。

getline次に、内側のループの前にイニシャルを配置して、最初の行をスキップします。

第三に、 には何も追加しませんtotalPrice。そして、内側のループ内で毎回印刷します。ループのに印刷するべきではありませんか?

したがって、次の擬似コードのようなものに変更します。

if (invoice.isopen())
{
    print_header();

    while (getline())
    {
        parse_line();
        print_current_item();
        totalPrice += itemPrice;
    }

    print_footer_with_total(totalPrice);

    invoice.close();
}
于 2013-11-13T10:36:47.080 に答える
0

getline の区切り引数を使用しないのはなぜですか?

for (string str; getline(file, str, '#'); ) {
  double price;
  file >> price >> ws;
  totalPrice += price;
  // handle input...
}
// print total etc.
于 2013-11-13T11:30:09.543 に答える