How can I exit from "getline()" without pressing any key?

Discussion in 'C++' started by caoliangbj, Jun 8, 2007.

  1. caoliangbj

    caoliangbj Guest


    When I capture the SIGINT event, I encounter a probelm.

    Please look at the following code, if you don't press any key, the
    'getline()' will block there all the time.

    When I press 'ctrl+c', the function 'getline()' still block there.

    My question is how can I exit from "getline()" while I just press 'ctrl

    #include <string>
    #include <iostream>
    using namespace std;

    static bool g_bRun = true;

    static void OnSIGINT(int)
    g_bRun = false;

    int main()
    Signal(SIGINT, OnSIGINT);

    string input;
    while (g_bRun) {
    if (getline(cin, input)) {
    cout << input << endl;

    cout << "exit." << endl;

    return 0;

    caoliangbj, Jun 8, 2007
    1. Advertisements

  2. The behaviour of the program upon receiving _any_ input is very much
    implementation- and platform-dependent. Please ask in the newsgroup
    for your OS. For example, on the OS I used to write for, Ctrl+C would
    not be converted into a signal for my program until the program tried
    to output something. Yes, I know, it might seem strange, but that's
    what it was.

    Victor Bazarov, Jun 8, 2007
    1. Advertisements

  3. I don't think there is a way of doing what you ask using the C++
    standard. There are plenty of platform dependant ways of doing it.

    The istream method "readsome" might help but you need to "wait" for
    input, readsome does not.
    Gianni Mariani, Jun 8, 2007
  4. caoliangbj

    Maulik Guest

    Hi! Thanks for asking the question to us.
    Buy the i would like to know the which version of software you are
    using? Bcaz you know that there are different kinds of software for
    the C++. For example i using the VB 6.0 and VB 2005 and both the thing
    are totally different you cant match the code if you write the code
    for the VB 6.0 you cant debug or run in the VB2005 it will give us an
    error or it will gives us warning.
    Buy the did you have tried to put anything like the following:
    1. cout.flush();
    2. system("pause");
    3. In case of return 0 write the return option.

    Hope this might help you.
    Maulik, Jun 8, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.