istream >> operator
Consider the following snippet:
1 2 3 4 5 6 7 8
|
void readFromAFile(string filename){
ifstream is(filename);
char ch;
while(is){
is>>ch;
cout<<ch;
}
}
|
Now, suppose the file contains "Hello!". When I call this function in my main it returns "Hello!!" Where is this extra "!" coming from?
After reading in the whole file, the last
is >> ch;
is failing. And after that, you still have
cout << ch;
.
Thus, you're printing the ch that was read before, in this case, the "!".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int main( int argc, char *argv[] )
{
std::ifstream is( "test" );
char ch;
while( is )
{
if( ! ( is >> ch ) )
break;
std::cout << ch;
}
std::cout << '\n';
return 0;
}
|
Gotcha. Thanks Lynx876!
You're welcome! Happy coding (:
Topic archived. No new replies allowed.