开发者

Problem with consecutive cin's

#include<iostream>

int main()
{
    int x, y;
    cin >> x ;  
    cin >> y ;   // This gets ignored
}

Hi in above prog after pressing Ctrl-D during first cin second cin gets ignored. how i can make second cin work after pressing ctr-D during first cin. cin.ignore() and cin.clear(开发者_StackOverflow中文版) doesn;t seem to work.

My question is that if im pressing ctrl-D during first cin bascially i am leaving eof char in i/p stream which is not going to be read and it reamins there. now can't i remove this character from the stream so that it's ready again for input. if not what's the exact reason behind it.


Ctrl-D is for end-of-file. In this case, it indicates the end of the stdinstream, which means nothing is to be read again.


Pressing Ctrl+D signals that you have reached the end of input (end of file). That obviously means that the next input operation doesn't even have to try, because there can't be anything more to read.

If you don't want to terminate the input stream, just don't press Ctrl+D!


Ctrl-D signals the end of transmission or end of file. Using it will prevent all further reads from the standard input (std::cin in this case).


For safer more robust and reliable code always check the stream state before and after reading, especially after reading.

An example code fragment:

int x;
int y;

int main(void)
{
    if (!(cin >> x))
    {
        cerr << "Error reading first value." << endl;
        return EXIT_FAILURE;
    }
    if (!(cin >> y))
    {
        cerr << "Error reading second value." << endl;
        return EXIT_FAILURE;
    }
    cout << "First number: " << x << endl;
    cout << "Second number: " << y << endl;
    return EXIT_SUCCESS;
}

Remember that a read may fail for other reasons than EOF. In your case the "cin >> x" may fail because the user entered something that is not a number, such as a letter or symbol.


Try this: When you found the EOF, reset the stream with

clear(eofbit)

I know you said you tried

clear()

but that makes me assume that you called it without parameters which defaults to:

clear(goodbit)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜