1

これが私のプログラムの仕組みです。ユーザー入力を求めるプロンプトが表示され、数字以外が検出されると、ループが停止します。これが私のコードです:

int size = 0;
float number;
float total = 0;
vector <float> data;

//prompt user to enter file name
string file;
cout << "Enter a file name : " ;
cin >> file ;
//concatenate the file name as text file
file += ".txt";

//Write file
cout << "Enter number : ";
ofstream out_file;
out_file.open(file);
while(cin >> number)
{
    data.push_back(number);
    size++;
}

cout<< "Elements in array are : " ;
//check whether is there any 0 in array else print out the element in array
for (int count = 0; count < size; count++)
{
    if (data.size() == 0)
    {
        cout << "0 digit detected. " << endl;
        system("PAUSE");
    }else
    {
        //write the element in array into text file
        out_file << data.size() << " " ;
        cout << data.size() << " ";
    }
}
out_file.close();

ただし、多少の誤差があります。たとえば、1,2,3,4,5,g と入力すると、配列が 1,2,3,4,5 としてテキスト ファイルに書き込まれるはずです。ただし、代わりに 5,5,5,5,5 と表記されています。push_back を間違って使用しているのだろうか? ガイドをいただければ幸いです。

前もって感謝します。

4

2 に答える 2

2

この行はあなたが間違っているところです:

out_file << data.size() << " " ;

エントリにデータではなくベクトルのサイズを挿入しているだけです...

data.size()(実際には、出力ループのみをチェックしています)

于 2013-05-17T10:01:02.413 に答える