C++ - How to ifstream a user-inputed file
For a fun text rpg project I'm working on, I want to know how to have the user input a file. I've tried something like:
cin >> file;
ifstream world (file.c_str());```
However, whenever I try to compile, code that comes later that uses something like world >> room; doesn't work. It brings up a compile error saying something like world not defined. Any ideas?
sounds like it's probably a scoping issue. you probably need to globally declare world or put it in the same set of { } that it is used later.
scoping works as such: variable are recognized downwards e.g.
int a = 1; if (true) { cout << a; }
that works
variables are NOT recognized upwards e.g.
if (true) { int a = 1; } cout << a;
that wont work
This is dumb, it's kind of impossible unless I pass it to each function because it is using a bunch of functions and the scope is lost. Also, the thing that was losing scope wasn't a function, it was a while loop that was 2 lines down. Also, you can't have cin outside of a function, so declaring it globally is impossible.
This works sort of. If you get a correct file on the first try, it'll open. However if you enter a wrong file, then a right one, it doesn't work. I can't figure out what is going on, ideas?
{
printf("Please enter a file to open (world.erp)\n");
string file;
getline(cin,file);
cin.clear();
system("cls");
world.open(file.c_str());
if(!world.is_open())
{cout << "Unable to find " << file << endl;
} else {break;}
}```