detecting end of input with cin

前端 未结 6 1488
梦毁少年i
梦毁少年i 2020-12-10 06:13

I want to read a line of integers from the user. I\'m not sure how to check to see if the input has ended. For example I want to be able to do something like



        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 07:05

    It is very straightforward. All you need to do is perform the extraction as the condition:

    while (i < MAX_SIZE && std::cin >> x[i++])
    

    if the extraction fails for any reason (no more characters left, invalid input, etc.) the loop will terminate and the failure will be represented in the stream state of the input stream.

    Considering best practices, you shouldn't be using static C-arrays. You should be using the compile-time container std::array (or std::vector if the former is not supported).

    Here is an example using std::vector. It also utilizes iterators which does away with having to explicitly create a copy of the input:

    std::vector v{ std::istream_iterator{std::cin},
                        std::istream_iterator{}};
    

提交回复
热议问题