0

Given a file that contains one integer per line, I am trying to use this code to read the file and store the numbers in a vector.

Strangely, after finishing reading the file, my program is printing the string "stoi". Is this just a behavior of std::stoi? I couldn't find anything about this in documentation.

I am using g++ 6.2.1.

Here is the relevant code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

void usage() {
    std::cout << "Usage: ./binary_tree [FILE]\n";
}

int main(int argc, char* argv[]) {
try{
     if (argc <= 1) {
         usage();
         return 1;
     }

     std::ifstream inputFile;
     inputFile.open(argv[1], std::ios::in);

     if (!inputFile.is_open()) throw std::runtime_error("Failed to open file");

     std::string line;
     std::vector<int> nums;

     while(!inputFile.eof()) {
         getline(inputFile, line);
         int num = std::stoi(line);
         nums.push_back(num);
     }

     // Clean up
     inputFile.close();
     return 0;
}

catch(const std::exception& e) {
    std::cerr << e.what() << std::endl;
}
}
  • 1
    Please edit code so it's copy-pastable and compiles (e.g. what is BinarySearchTree?). Also you don't need to call close() explcicitly, that's done in ifstream's destructor. And finally which compiler are you using? – stijn Oct 27 '16 at 13:28
  • 3
    [`while(!inputFile.eof())` is wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). This might not be the cause of your issue, but it certainly is a bug. – Quentin Oct 27 '16 at 13:33
  • 1
    You probably hit an exception in `stoi`, and the text of that exception is printed out in your catch clause. Worth adding another token to your `cerr` command to confirm that. And, that likely occurs due to an issue with the `while` above that was pointed out by Quentin. – RomanK Oct 27 '16 at 13:39
  • Ah-yes, that was causing a problem. I changed the condition of the while loop to (inputFile >> num) and just did a push_back of that number. If I do a range-based loop to print the numbers in the vector, I get a "%" which I'm guessing is from the EOF? – cafeclimber Oct 27 '16 at 13:46
  • Not sure - I don't see how you would get a '%' from stoi. Maybe something wrong with the range-based loop. I think we can close the question though at this point, as your problem was solved? – RomanK Oct 27 '16 at 14:03
  • I'm no longer using stoi, but yes problem solved and can be closed. Thanks! – cafeclimber Oct 27 '16 at 14:05
  • 1
    @Quentin - Can you post your comment as an answer, so that it can be accepted? – RomanK Oct 27 '16 at 14:08

0 Answers0