-1

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?!

2
  • My guess would be that you input file does not contain integers (binary coded) but ASCII text. So you should convert. No sure, though... Jul 11, 2015 at 8:11
  • Works for me: ideone.com/SL8Lc9 Are you sure the file is opened correctly? Jul 11, 2015 at 10:17

1 Answer 1

0

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.

1
  • Thanks everyone. It started working in the morning without any change... This is odd. I'm using Xcode on mac, and I have nothing to blame but one of these two... lol
    – GrinNare
    Jul 11, 2015 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.