Alex Ware Alex Ware - 2 months ago 8
C++ Question

Simple C++ file reading program only returns garbage

I'm a beginner programmer and I'm having an issue that I'm sure is just caused by a stupid mistake but I for the life of me can't figure out what it is. I've tried searching solutions on this site but none of the remedies I found worked for my problem

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inputFile;
float num;
inputFile.open("numbers.txt");
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;
inputFile >> num;
cout << num << endl;

inputFile.close();

return 0;
}


So it's a simple code, and I'm reading the textbook I have verbatim on what to do but whenever I run the code it just churns out garbage versus the numbers.txt file I created using a different program.

If anyone can tell me where my mistake is, or tell me where to look up this problem I'd appreciate it. Thanks in advance

Edit: I used a different code to create the file and I can confirm that the file was created successfully in .txt format

Answer

Please check if the file is opened correctly. Add the below code after inputFile.open("numbers.txt");

if(inputFile.fail())
{
    cerr<< "Error Opening File" << endl;
    exit(1);
}

Also try giving the absolute path of the file if there is an error in opening the file.

Comments