-1

私はプログラミングを始めたばかりで独学しようとしていますが、私のカウンターは必要以上に 1 つ表示しています。22 と表示されているはずが、23 と表示されています。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

//Main and variable data type initializing

void main()
{    float c,l,x,y,z;
    int count;
    string input, output;
    string finput, foutput;
    fstream i,o;    //i = input file;    o = output file;
//Getting the name of the files

    cout << "XZY Multiply Program\n" << endl;
    cout << "Enter the input file name:  c:/";
    cin >> input;
    cout << "Enter the output file name:  c:/";
    cin >> output;

//inserts the beginning of the file and file extension.

    finput = "c:/" + input;
    foutput = "c:/" + output;

//Opens files

    i.open(finput.data(),ios::in);
    o.open(foutput.data(),ios::out);

//Initialize count and sum of variables

    count = 0;
    x=0;
    y=0;
    z=0;

//loop through input file

    while(!i.eof() && !o.eof())
    {   count++;
        if (i.good() && o.good())
        {

                i >> c;
                i >> l;   
                o << fixed << showpoint << setprecision(4);
                o << setw(7) << c;
                o << setprecision(2);
                o << setw(9) << l;
                o << setprecision(3);
                o << setw(10) << (l*c) << endl;

// Adds columns
                x = x+c;
                y = y+l;
               z = z+(l*c);

        } 
         else
        {
        cout << "no good";
        }

    }
     i.close();
     o.close();



    //Display the output of the counter and Sums of columns
            cout << fixed << showpoint << setprecision(2);
            cout << "\n" << count << " lines in file " << endl;
            cout << "X sum = " << setw(8) << right << x << endl;
            cout << "Y sum = " << setw(8) << right << y << endl;
            cout << "Z sum = " << setw(8) << right << z << endl;


}

  7.2830     84.40
  9.1327    124.02
  7.2619    133.16
  6.2527     43.96
  4.2160     24.08
  5.2724     57.80
  5.2025     73.89
 -9.9500     80.53
  0.2790    -12.43
  2.2115      3.37
  3.1222     13.63
 16.2413    223.01
 -4.2026     33.78
 -7.1914     42.89
  4.1417     53.42
  6.1714     61.66
  9.2516     73.68
 15.2419    383.66
  6.2715     93.53
 -3.2016      3.46
 12.2013    213.63
  3.1824     23.85
4

2 に答える 2

4

.eof()またはをループ条件として使用.good()すると、この場合のように、ほとんどの場合、バグのあるコードが生成されます。

むしろ、次のように、入力を実行し、ループ状態でその結果を確認します。

while(i >> c >> l)
{   count++;
    o << fixed << showpoint << setprecision(4);
    o << setw(7) << c;
    ...

参照:

于 2012-04-12T13:12:57.810 に答える
0

入力ファイルから最後の番号を読み取った後、ファイルの終わりはまだ見られていないと思います。追加してみる

if (!i.good()) break; 

各入力ステートメント ( >>) の後、失敗した入力の後にループ本体が実行されるのを防ぎます。

于 2012-04-12T12:54:11.563 に答える