Test if stdin has input for C++ (windows and/or linux)

后端 未结 3 933
别跟我提以往
别跟我提以往 2020-12-03 17:45

I basically want to test if stdin has input (like if you echo and pipe it). I have found solutions that work, but they are ugly, and I like my solutions to be clean.

相关标签:
3条回答
  • 2020-12-03 18:02

    Would this not work?

    std::cin.rdbuf()->in_avail();
    
    0 讨论(0)
  • 2020-12-03 18:16

    Here's a solution for POSIX (Linux): I'm not sure what's the equivalent of poll() on Windows. On Unix, The file descriptor with number 0 is the standard input.

    #include <stdio.h>
    #include <sys/poll.h>
    
    int main(void)
    {
            struct pollfd fds;
            int ret;
            fds.fd = 0; /* this is STDIN */
            fds.events = POLLIN;
            ret = poll(&fds, 1, 0);
            if(ret == 1)
                    printf("Yep\n");
            else if(ret == 0)
                    printf("No\n");
            else
                    printf("Error\n");
            return 0;
    }
    

    Testing:

    $ ./stdin
    No
    $ echo "foo" | ./stdin
    Yep
    
    0 讨论(0)
  • 2020-12-03 18:24

    I'm not sure, but does _kbhit() do what you need?

    0 讨论(0)
提交回复
热议问题