[C++] Switch statement to open a text file
2 posters
RUSES :: Part 1 :: Programming :: Coursework
Page 1 of 1
[C++] Switch statement to open a text file
So depending on the game chosen a different text file should open up. The compiler has serious beef with this (the rest of the code is unneccesary to understand the problem).
I was wandering if anyone knew of a way around this to get it to compile as there is no way both things can be called so there shouldn't be a clash really.
switch(game)
{
case 1: ifstream myFile("level1.txt"); countto = 25; break;
case 2: ifstream myFile("level2.txt"); countto = 36; break;
}
Pre-thanks for any help given
I was wandering if anyone knew of a way around this to get it to compile as there is no way both things can be called so there shouldn't be a clash really.
switch(game)
{
case 1: ifstream myFile("level1.txt"); countto = 25; break;
case 2: ifstream myFile("level2.txt"); countto = 36; break;
}
Pre-thanks for any help given
lee- Posts : 22
Join date : 2012-02-23
Re: [C++] Switch statement to open a text file
Scoping issues, try:
string directory = "";
switch(game)
{
case 1: directory = "level1.txt"; countto = 25; break;
case 2: directory = "level2.txt"; countto = 36; break;
default: cout << "Level file doesn't exist" << endl; break;
}
ifstream myFile(directory);
string directory = "";
switch(game)
{
case 1: directory = "level1.txt"; countto = 25; break;
case 2: directory = "level2.txt"; countto = 36; break;
default: cout << "Level file doesn't exist" << endl; break;
}
ifstream myFile(directory);
Alex- Posts : 67
Join date : 2012-02-23
Location : Come at me bro
Re: [C++] Switch statement to open a text file
Thanks Alex that worked a treat , I had a similar problem with switches in one of the labs and I get why it didn't work now
lee- Posts : 22
Join date : 2012-02-23
Re: [C++] Switch statement to open a text file
No problem Do you understand why your code didn't work, because this mistake is easy to make?
Alex- Posts : 67
Join date : 2012-02-23
Location : Come at me bro
Re: [C++] Switch statement to open a text file
I think it's because when c++ compiles it doesn't skip over initialisers in switch statements so even though logically it should only open one - the compiler sees it as trying to open two seperate ones?
lee- Posts : 22
Join date : 2012-02-23
RUSES :: Part 1 :: Programming :: Coursework
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum