简体   繁体   中英

Why does std::istream::gcount return one char more than expected

I'm just wondering why this standard function is returning a char count of 9 for the sample code at cplusplus.com

// cin.gcount example
#include <iostream>     // std::cin, std::cout

int main () {
  char str[20];

  std::cout << "Please, enter a word: ";
  std::cin.getline(str,20);
  std::cout << std::cin.gcount() << " characters read: " << str << '\n';

  return 0;
}

Please, enter a word: simplify

9 characters read: simplify

Why is this returned as 9 characters?

Because of the enter key. When you press enter, a newline character ( '\\n' ) is entered into the stream. getline reads up to that newline, stores the text in the array, and then reads and discards the newline. Thus, when you read simplify , you actually read simplify\\n which is 9 characters.

cplusplus.com is generally considered by many people to be a poor site for C++ documentation. You really should use cppreference.com instead.

For instance, cppreference's istream::getline() documentation states the following:

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).

If the function extracts no characters (eg if count < 1 ), setstate(failbit) is executed.

cplusplus's istream::getline() documentation states the following instead:

The delimiting character is the newline character ('\\n') for the first form, and delim for the second: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s .

...

The number of characters successfully read and stored by this function can be accessed by calling member gcount .

Which is a little misleading, as it implies that getline() only counts characters that are stored in the user's buffer, but the delimiter is not stored in the buffer and yet it still counts towards gcount() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM