Adding items to a vector

I have the following code:

1
2
3
4
5
6
7
8
9
10
11
	vector <int> myVector;
	int theData;

	ifstream myFile;
	myFile.open("TheData.txt");

	do
	{
		myFile >> theData;
		myVector.push_back(theData);
	}while(!myFile.eof());


Is it possible to consolidate the following two lines in to one statement?

1
2
myFile >> theData;
myVector.push_back(theData);
No, it is impossible if do not use the comma operator because expression myFile >> theData has a different type than theData. And moreover two lines make the code more clear.
If to use the comma operator then it is possible to write

myVector.push_back( ( myFile >> theData, theData ) );


I would rewrite your code snip the following way

1
2
3
4
	while ( myFile >> theData )
	{
		myVector.push_back(theData);
	}
Last edited on
Thanks. And yes, I would normally write the code the way you suggested, but for this specific task, I have to get only the integers from the file. The final code looks like this:

1
2
3
4
5
do
{
	if(myFile >> theData)
		myVector.push_back(theData);
}while(!myFile.eof());
That's essentially the same as Vlad's... except the failbit can be set without the eofbit being set, so you've got an endless loop there if the conditions are right for it.
Topic archived. No new replies allowed.