Im trying to read the contents of a file in C++, but when I go to run the program it keeps failing. Not sure if this is because I’m using ubuntu linux.
Image of my code i used
Seems basic enough but for some reason the file never opens and continues to fail
// This program reads data from a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile;
MyReadFile.open("nums");
if(!MyReadFile){
cout << "Failed" << endl;
}
else
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
}
New contributor
Dokkaebi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1