Так работает моя программа. Он запрашивает ввод пользователя, как только не распознается цифра, цикл остановится. Вот мой код:cin to vector in C++
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? Любые руководства будут оценены.
Заранее спасибо.
Вам не нужно отслеживать размер самостоятельно; 'std :: vector' делает это за вас. Идиоматическим способом вывода содержимого вектора будет 'std :: copy (data.begin(), data.end(), std :: ostream_iterator (out_file," "));' –