Total N00b here with C++ question

+1 Alexxis Lee · January 9, 2015
Hi, 

I am trying to read a number from a text file on my desktop.  I am required to use Microsoft Visual Studio Express - when I try and debug it, I get this:  -858993460.  (it's a test- that's why I am only trying to read in one number).

Here is the code:

#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
 ifstream inFile;
int playerNum;
inFile.open ("C:\\stat.txt");

inFile >> playerNum;
cout << "here is the number\n" <<playerNum << endl;

inFile.close();
system ("pause");
return 0;
}

Is there anything that I have to do with the txt file or should I just learn how to say, "Would you like fries with that?"

Thanks in advance!

Tess

Post a Reply

Replies

Oldest  Newest  Rating
0 Milan Obrenovic · January 9, 2015
1) Why is it hard to use the code tags so we can see your code a lot clearer?
2) That error displays because your file is empty. If you want it to display something on the screen FROM that file, write something in the file first.

3) Here's a working example in Visual Studio Express 2010. This is how I would do it:
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
   freopen("stat.txt", "r", stdin);

   int playerNum;
   cin >> playerNum;

   cout << "Here is the number\n" << playerNum << endl;

   system("pause");
   return 0;
}


And this is a fixed solution of your example:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
   ifstream inFile;
   int playerNum;
   inFile.open ("stat.txt");

   inFile >> playerNum;
   cout << "here is the number\n" <<playerNum << endl;

   inFile.close();
   system ("pause");
   return 0;
}

The file contains something like "1337", and this will output "1337".

Important: make sure your file is located in the same directory as your main.cpp
0 Alexxis Lee · January 9, 2015
It isn't that it is hard to use code tags, I just don't know what they are or how to use them- I will try and learn before I post a help for request again.

So, the answer to my question is that there isn't anything in my file, right? My file has a number in it. One number.  The number is 10. It is saved as a .txt file.  

I also can't use this- freopen("stat.txt", "r", stdin);

We don't use that and we are supposed to use fstream.

So really, my problem might be that the file is not located in the same directory as my main.cpp file.

You have been quite helpful. Thank you so much for your time!
0 Milan Obrenovic · January 9, 2015
Yes, you can use either  fstream   or  freopen, I just find freopen more elegant. In your location to the file, you wrote

inFile.open ("C:\\stat.txt");


If your file is located in C drive, move it to the location where your main.cpp is, and then just set

inFile.open ("stat.txt");

  • 1

C++

107,344 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator