1
#include <iostream>
using namespace std;


int main()
{

    int a ;
    while ( ( a = cin.get() ) != EOF )
    {

       cout << "hi" <<endl;

     } // end while


}

I wonder why this outputs "hi" twice whenever I input once.

for example

input : 1 output : hi hi

mintbox
  • 167
  • 1
  • 14

2 Answers2

2

Your input actually consists of two characters: the character 1 followed by a newline.

Try piping in the contents of a file that only contains one byte, or a one-letter string without newline, and you'll see only one "hi".

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
1

Add a line of code to print the value of a. That will help you understand what the input values the program sees:

int main()
{
    int a ;
    while ( ( a = cin.get() ) != EOF )
    {
       cout << a << endl;
       cout << "hi" << endl;    
    } // end while    
}

If your systems uses ASCII values for char encoding you can find out what the output means by looking up the ASCII table.

R Sahu
  • 196,807
  • 13
  • 136
  • 247