-
Read File in Switch
The following piece of code (which will read a number from input.txt, provided of course that you enter 0) will compile and run fine:
Code:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
int n;
cin >> n;
switch (n)
{
case 0:
char buffer[256];
ifstream inputfile ("input.txt");
if (! inputfile.is_open())
{
cout << "Error opening file";
}
while(! inputfile.eof() )
{
inputfile.getline (buffer,100);
n = atol(buffer);
cout << n;
}
break;
}
}
However, if I add another case into the switch, it will not compile:
Code:
switch (n)
{
case 0:
char buffer[256];
ifstream inputfile ("input.txt");
if (! inputfile.is_open())
{
cout << "Error opening file";
}
while(! inputfile.eof() )
{
inputfile.getline (buffer,100);
n = atol(buffer);
cout << n;
}
break;
case 1:
break;
}
Why does adding that other case make it not work?
P.S. I know the code is very strange... it is part of a program I am writing that does make sense, but I have identified this as the problem.
Thanks!
-
When you declare variables inside a switch case, you use brackets ( { } ) I believe. Thus making your code more like:
Code:
switch (n)
{
case 0:
{
somevar var;
... code here....
break;
}
case 1:
....more stuff
break;
}
Edit: You know just for kicks I should mention you should knock the .h from your header file declarations. It's some C++ ANSI standard. http://www.google.com/search?q=c%2B%2B+header+files
-
> Why does adding that other case make it not work?
Well stating OS, Compiler and error messages would be a start.
> #include <iostream.h>
If your compiler doesn't support this, then you need to upgrade.
#include <iostream>
using namespace std;
> while(! inputfile.eof() )
Read the FAQ as to why eof() in control loops doesn't do what you think it does.
-
I enclosed the offending case in brackets and it now works.
Thanks guys!