Question

I'm in an introductory C++ class and I am having a strange issue with reading from an input file. I have a text file named "inputFile.txt" that only contains the value of 5. The following code is meant to open the file, read the value of 5 and assign it to the variable 'a' then print the value of 'a' to the console. No matter what I do, the code always prints out "528".

#include<fstream>
#include<iostream>

using namespace std;

int main()
{
   int a;

   //create and open file
   ifstream input;
   input.open("inputFile.txt");

   //read value of 5 from file and assign to a
   input >> a;

   //print value of a       
   cout << a << endl;

   system("PAUSE");
}

I hate to ask this question because it's so basic that I feel I MUST be overlooking something extremely simple. However, I am at a complete loss right now and no amount of web searches has given me any enlightenment. If you could point out what I've done wrong I would really appreciate it.

Was it helpful?

Solution

Nothing seems to be wrong with your code. I ran it exactly as is on my PC and it worked 100%.

Possible problems:

  • You have the file stored in the wrong place
  • The file isn't named properly
  • The file actually contains "528"
  • Your IDE is experiencing some glitch
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top