Disclaimer: this question is directly related to programming exercise from a text book.
I'm working on a C++ programming exercise from a text book but could not figure out how to get it working. Hope if anyone could point out the error in my code. Here comes the problem...
"Use an istream_iterator, the copy algorithm and a back_inserter to read the contents of a text file that contains int values separated by whitespace. Place the int values into a vector of ints. The first argument to the copy algorithm should be the istream_iterator object that's associated with the text file's ifstream object. The second argument should be an istream_iterator object that's initialized using the class template istream_iterator's default constructor - the resulting object can be used as an "end" iterator. After reading the file's contents, display the contents of the resulting vector."
I built following code. The code compiles, but does not do anything.
int main()
{
std::vector< int > testVector;
std::ifstream inputFile( "/Users/GrinNare/Documents/Study/C++/Chapter 16/Chapter 16/16_10_Text_File.txt", std::ios::in );
std::istream_iterator< int > inputFromFile( inputFile );
std::copy( inputFromFile, std::istream_iterator< int >(), back_inserter( testVector ) );
for ( int i = 0; i < testVector.size(); i++ )
std::cout << testVector[i] << "\t";
std::cout << std::endl;
return 0;
}
Text file contains the following: "12 23 43 34"
I tried to debug the code and noticed that values in the text file are not read properly into int vector because they are separated by whitespace, not new line.
Could anyone please help?!
I tried your code in ideone, changing to read from std::cin
. It works as expected.
The only way I could reproduce your issue was when I used a file that failed to open as input.
So I guess adding the following will show what's going on:
// after opening the file
if (! inputFile) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}
Probably you have a typo in that path.