0

I'm attempting to open a file and read a series of ints from it in C++. I was under the impression that this could be done by simply using inputfile >> variable. However, even the first item is reading in incorrectly. I wrote the simplest possible code to replicate my problem.

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char **argv) {
    int n;

    ifstream inputfile("input.txt");
    inputfile >> n;

    cout << "NUMBER IS: " << n << endl;

    return 0;
}

The input file is simply a text file containing the number 4. However, I get a different large number out every time I test the code. What's the issue?

tjcoats97
  • 37
  • 3
  • 2
    There was probably an error reading the file. See [ifstream Error Checking](http://stackoverflow.com/questions/13446593/c-ifstream-error-checking) - check for errors after opening and after reading. – interjay Sep 05 '16 at 21:26
  • How is the number encoded? It is in binary format? If so, it is big endian or little endian? Is it an ASCII representation of a number? – wallyk Sep 05 '16 at 21:27
  • Check if the input operation was actually good like `if(inputfile >> n) ...`. There are chances your file wasn't properly opened. – πάντα ῥεῖ Sep 05 '16 at 21:29
  • It appears that the file isn't opening successfully after I implemented some error checking. What can I do about this? – tjcoats97 Sep 05 '16 at 21:32
  • Where is the file located? Is it in the current working directory (where you run the executable)? If not, try adding an absolute path to the file. Other considerations are: is the name of the file input.txt (spelled correctly) and is there read permission for the file? – aichao Sep 05 '16 at 21:36
  • The file is located in the current working directory. For some reason it worked when I removed the .txt extension in the code. – tjcoats97 Sep 05 '16 at 21:38
  • 1
    @tjcoats97: Then the file is not called `input.txt`, but `input`. – Lightness Races in Orbit Sep 05 '16 at 21:47

1 Answers1

1

Add checks like this:

if(inputfile>> n)
{
     //Code
} else
{
    cout << "Failed!";
}

Also, check the file was opened:

ifstream inputfile("input.txt");
if (!inputfile)
{
    cout << "Failed opening file!";
    return -1;
}
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • I did this, and it appears that the file isn't opening properly. What can I do to address this? Why would the file not be opening? – tjcoats97 Sep 05 '16 at 21:35
  • 2
    @tjcoats97 Maybe it's not in your current directory. Try using the full pathname of the file. – Barmar Sep 05 '16 at 21:40
  • @tjcoats97 check right directory, right name, right extension, no extension? Have you tried these? Spelling errors can be fatal – Arnav Borborah Sep 06 '16 at 00:37