while loop conditions

I have been trying to do this for a few hours and i cant seem to stop the loop at the end of the file please help me.

int main ()
{
char x;
int count=0;
ifstream infile;
infile.open("exercise4.dat");
while(count != ' ' || count != '\n')
{
infile.get(x);

if (x != ' ' )
{
if(x != '\n')
{
count++;
}
}
cout << x;
}
infile.close();
cout<<endl;
return 0;
}

The loop just repeats the last character in the file. i have tried to stop it by setting the loop to the right amount of characters in the file but this is not practical as i would like to be able stop it with any size of file.
this is undecleared
ifstream infile;

I don't get why you're comparing count to characters since count is an integer. I think what you want to use is the function .eof() (end-of-file function). I don't understand it too well but in short it returns true when there is no more data to read and returns false otherwise. I haven't tested the code below but it should give you a rough idea of what you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main ()
{
short count;
char x;
ifstream infile;
infile.open("exercise4.dat");
infile.get(x);
while(!infile.eof())//while infile still has some data to read
{
cout << x;
infile.get(x);
if(x != '\n' && x != ' ')
{
count++;
}

}
infile.close();

cout<<endl << "The number of non-white space characters encountered: " << count << endl;
return 0;
}


In the future please put you code in the above format by pressing the "<>" button to the right of where type your posts so that it's easier to read and help you.
Topic archived. No new replies allowed.