Cannot open txt files c++

I made a very simple program just to check if the file would open because this other one would not. I created the file input2.txt with only “Rob” in it to test with this code in help.cpp:

#include
#include

using namespace std;
int main (){

ifstream in(“input2.txt”);
string name;

in.open(“input2.txt”);
if(!in){

cout << “booo” << endl;
}
in >> name;

in.close();
cout << name;

return 0;
}

The output was “booo” I don’t see what im doing wrong.

Welcome to the Ask community, @oliviaMott!

For anyone else trying to help, I believe this is the Repl.

I think first of all the input2.txt shouldn’t be inside the folder. I think when the code is compiled, the output isn’t in the folder, so it’s not trying to access the file in the actual folder, it’s trying to access a file that doesn’t exist. Also, instead of if (!in) I think you should do if (!in.is_open()) which checks if the file has been opened successfully.

I forked your Repl and after moving input2.txt out of the hw1help folder and changing the if statement to if (!in.is_open()) it seemed to work as expected.

In future, posting the link to your Repl’s cover page, or at least formatting the code using markdown would help the community help you. You can create a code block using three backticks, followed by the code, then ending with three backticks:

#include <iostream>
using std as namespace;

int main() {
	cout << "Hello world!" << endl;
	return 0;
}

You can also specify the language after the first three backticks, like cpp for C++.

Raw
```cpp
#include <iostream>
using std as namespace;

int main() {
	cout << "Hello world!" << endl;
	return 0;
}
```
2 Likes