tags:

views:

98

answers:

5

Hi,

I am using the following code:

#include <stdio.h>
#include <iostream>
using namespace std;

int main ()
{
    char c ;
    c = cin.get() ;
    do {
        cout.put(c) ;

        c = cin.get() ;
    } while ( !cin.eof()) ;

    cout << "coming out!" << endl;
    return 0;
}

Problem with the above code is, its not getting out of loop, which means its not printing "coming out". Anybody can help why it is so? I am testing this program on mac and linux.

Thanks

+1  A: 

You need to press CTRL-Z to simulate EOF (End-of-File) and to exit the loop.

If you don't press CTRL-Z, the loop will continue to run forever.

Igor Popov
Or CTRL-D on non-Microsoft platforms.
sepp2k
+5  A: 

It does print "coming out" provided that it gets the end-of-file. It will go out of the loop if you redirect a file to it with

./program < file

or send the end-of-file yourself, by hitting ctrl+d (linux) or ctrl+z (dos)

Michał Trybus
Well if i use the following command to run it, it came out of it. ./main < input.txt >output.txt . But is there anyway if i can give input on command prompt? Thanks
itsaboutcode
If i hit ctrl+d (linux), its not printing "coming out"
itsaboutcode
As others have mentioned (for dos/windows) and I have just added, you can always tell the program when you end transmitting information to it
Michał Trybus
You have to make sure you hit it on an empty line (just after enter)
Michał Trybus
+2  A: 

Standard in never hits EOF, unless you press Ctrl+Z.

Therefore, cin.eof() is always false.

To fix it, press Ctrl+Z to send an End-Of-File character.
Alternatively, you could change the condition. (eg, while(c != '\n'))

SLaks
Though your answer while(c != '\n') works on terminal, but it stuck when i try to give input using file. Thanks anyways.
itsaboutcode
SLaks
You are great man!
itsaboutcode
+1  A: 

Works perfectly well here :) If you run this in a terminal you have to send EOF to this terminal. On *nix this would be Control + D. I cannot say anything about Windows unfortunately.

Edit: As others have pointed out: Ctrl + Z would be the Windows way of sending EOF.

pmr
A: 

I'm going to make a guess about intent, because there's nothing wrong with that code but it's probably not what you intended, and will also suggest a while loop uhhh.. while I'm at it.

#include <stdio.h>
#include <iostream>
using namespace std;

bool is_terminator(char ch)
{
    return ch != '\n' && ch != '\r';
}

int main ()
{
    char ch;
    while (cin.get(ch) && !is_terminator(ch) )
        cout.put(ch);

    cout << "coming out!" << endl;
}