-
read files
I'am having trouble reading files. can someone tell me whats wrong with this.
Code:
#include<iostream>
#include<fstream>
int main(void)
{
int i;
int j;
int num;
int up[8] = {24,49,74,99,124,149,174,200};
int low[8] = {0,25,50,75,100,125,150,175};
int ans[8] = {0,0,0,0,0,0,0,0};
ifstream infile;
infile.open("scores.c");
for(i = 0; i <= 26; i++) // there are 26 scores to check
infile >> num;
for(j = 0; j < 8; j++)
{
if( num <= up[j] && num >= low[j])
{
ans[j]++;
break;
}
}
for(j = 0; j < 8; j++)
cout << low[j] << " - " << up[j] << " = " << ans[j] <<endl;
infile.close();
}
-
can u say what is wrong with it, other than not accessing the std namespace for fstream, cout and endl it runs fine.
-
In the output I get only one file read instead of 26.
-
>ifstream infile;
>infile.open("scores.c");
I couldn't help but notice that you don't account for namespaces yet you still use current standard headers. This is sure to give you a slew of errors. Also, these two lines can be merged like so:
Code:
std::ifstream infile ( "scores.c" );
>for(i = 0; i <= 26; i++) // there are 26 scores to check
Then why are you looping 27 times? If you start at 0 and go until after 26, you'll go too far. Remember that the following is almost always a mistake:
Code:
for ( i = 0; i <= N; i++ )
And should almost always be this:
Code:
for ( i = 0; i < N; i++)
The same goes for any variation of the above two loops, if you start at 0 then you test for < N, if you start at 1 you test for <= N. But back to the loop, you read 26 scores (assuming you've fixed your loop) and throw away all but the last of them. Most likely this isn't what you wanted. :)
>for(j = 0; j < 8; j++)
I assume this loop checks some kind of score range with the number you read before. A comment here would be very nice.
>cout << low[j] << " - " << up[j] << " = " << ans[j] <<endl;
Both cout and endl are in the std namespace.
>infile.close();
Technically you don't need this as the destructor for ifstream closes the file for you.
-
I'am using JED, a g++ complier in linux, for some reason it works without namespace.