简体   繁体   中英

cin to vector in C++

This is how my program works. It prompts for user input, once non-digit detected, the loop will stop. Here is my code :

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();

However, there is some error. For example, I entered 1,2,3,4,5,g, it supposed to write the array as 1,2,3,4,5 into a text file. However, it written in 5,5,5,5,5 instead. I wonder am I using the push_back wrongly? Any guides would be appreciated.

Thanks in advance.

This line is where you are going wrong:

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

You are simply inserting the size of the vector rather than the data at the entry...

(In fact you are only checking data.size() in your output loop)

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();

Use the element rather then the size of the vector. Example:

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM