Reading two line continuously using getline function in c++

前端 未结 1 1878
清酒与你
清酒与你 2020-12-22 00:26

I was learning how to read strings with getline function.

I know that getline function read string as far as we don\'t hit enter or the size value in the getline para

相关标签:
1条回答
  • 2020-12-22 01:19

    std::istream::getline is being overloaded with data.

    According to cppreference,

    Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):

    • end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)
    • the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.
    • count-1 characters have been extracted (in which case setstate(failbit) is executed).

    Emphasis mine.

    cin.getline(line1,7);
    //                ^ This is count
    

    can read only 6 characters with the 7th reserved for the null terminator. "oranges" is seven characters, and this places cin in a non-readable error state that must be cleared before reading can be continued. Reading of the second line

    cin.getline(line2,7);
    

    instantly fails and no data is read.

    The obvious solution is

    cin.getline(line1, sizeof(line1));
    

    to take advantage of the whole array. But...

    Any IO transaction should be tested for success, so

    if (cin.getline(line1, sizeof(line1)))
    {
        // continue gathering 
    }
    else
    {
        // handle error
    }
    

    is a better option.

    Better still would be to use std::getline and std::string to almost eliminate the size constraints.

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