Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C++ - How to ifstream a user-inputed file


devilsson2010's Avatar
Member
0 0

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?

ghost's Avatar
0 0

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


devilsson2010's Avatar
Member
0 0

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.


ghost's Avatar
0 0

you declare the variable globally. and scoping is not dumb. scoping allows you to reuse variable names as well as saves memory, because when things go out of scope, they are destroyed.


devilsson2010's Avatar
Member
0 0

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(&quot;Please enter a file to open (world.erp)&#92;n&quot;);
string file;
getline(cin,file);
cin.clear();

system(&quot;cls&quot;);

world.open(file.c_str());
  if(!world.is_open())
	{cout &lt;&lt; &quot;Unable to find &quot; &lt;&lt; file &lt;&lt; endl;
	} else {break;}
}```

ghost's Avatar
0 0

perhaps trying closing and clearing the file. I don't know what the commands are in C but in C++ they are file.close() and file.clear()