RUSES
Would you like to react to this message? Create an account in a few clicks or log in to continue.
May 2024
MonTueWedThuFriSatSun
  12345
6789101112
13141516171819
20212223242526
2728293031  

Calendar Calendar


[C++] Switch statement to open a text file

2 posters

Go down

[C++] Switch statement to open a text file Empty [C++] Switch statement to open a text file

Post  lee Thu Mar 08, 2012 7:45 am

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 Smile
lee
lee

Posts : 22
Join date : 2012-02-23

Back to top Go down

[C++] Switch statement to open a text file Empty Re: [C++] Switch statement to open a text file

Post  Alex Thu Mar 08, 2012 8:03 am

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);
Alex
Alex

Posts : 67
Join date : 2012-02-23
Location : Come at me bro

Back to top Go down

[C++] Switch statement to open a text file Empty Re: [C++] Switch statement to open a text file

Post  lee Thu Mar 08, 2012 9:19 pm

Thanks Alex that worked a treat Very Happy , I had a similar problem with switches in one of the labs and I get why it didn't work now Smile
lee
lee

Posts : 22
Join date : 2012-02-23

Back to top Go down

[C++] Switch statement to open a text file Empty Re: [C++] Switch statement to open a text file

Post  Alex Thu Mar 08, 2012 9:22 pm

No problem Smile Do you understand why your code didn't work, because this mistake is easy to make?
Alex
Alex

Posts : 67
Join date : 2012-02-23
Location : Come at me bro

Back to top Go down

[C++] Switch statement to open a text file Empty Re: [C++] Switch statement to open a text file

Post  lee Fri Mar 09, 2012 7:21 am

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
lee

Posts : 22
Join date : 2012-02-23

Back to top Go down

[C++] Switch statement to open a text file Empty Re: [C++] Switch statement to open a text file

Post  Sponsored content


Sponsored content


Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum