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 回答
1
for (int count = 0; count < data.size(); count++) {
     if (data[count] == 0) {
         cout << "0 digit detected. " << endl;
         system("PAUSE");
     } else {
         //write the element in array into text file
         out_file << data[count] << " " ;
         cout << data[count] << " ";
     }
 }
 out_file.close();

使用元素而不是向量的大小。例子:

std::vector<int> yourVector;

yourVector.push_back(1);
yourVector.push_back(3);

cout << "My vector size: " << yourVector.size() << endl; //This will give 2

cout << "My vector element: " << yourVector[0] << endl; //This will give 1 
于 2013-05-17T10:03:23.957 回答