Urihel Coleman
Urihel Coleman

Reputation: 71

Why is my txt file failing to open in C++?

I'm trying to open a .txt file that contains integer values 0-9 each individual number on its own line till the last number is 9. When i run the code i'm using im running into an issue with opening my txt file. Based on the if and else statement provided its failing to open what is causing this and what method can i use to open my notepad .txt file.

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

int main()
{
ifstream infile; //Container for the file
infile.open("assignmentG1.txt"); //Name of the file you want to open
string stringFromFile; //string variables to store extracted strings


if(infile.fail())  {//Display error if the file failed to open
cout<<"Input file failed to open";
}
else
{
getline(infile, stringFromFile);
}
cout<<stringFromFile;
}
input file failed to open.

Upvotes: 1

Views: 1366

Answers (2)

user6710094
user6710094

Reputation: 77

Your file should be at correct path if your project name is suppose project_name so keep the file at /project_name/project_name/assignmentG1.txt . Assuming you are using visual studio.

Upvotes: 0

J-Christophe
J-Christophe

Reputation: 2070

The code works as expected, just make sure you execute the compiled program from the directory where the text file exists.

Assuming the source code is added to a file named main.cpp and running on Linux or macOS with gcc compiler installed, the following works:

echo "Hello" > assignmentG1.txt
g++ main.cpp -o main
./main
Hello

Upvotes: 2

Related Questions