std::get() problem

I have the following code. I execute it doing this
1. write "abc"
2. hit enter
and after this abc="abc", but nl="". I expected nl to be equal to the newline character, because the previous get() is said not to remove the delimiting (newline) character from the stream. Why is nl not equal to newline character?

1
2
3
4
5
6
7
   char abc[20];
   std::cin.get(abc,20);
    
   char nl[256];
   std::cin.get(nl,2);
  
   std::cout<<"|"<<nl<<"|";
Last edited on
From:

istream::get
http://www.cplusplus.com/reference/istream/istream/get/

(2) c-string
Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or the delimiting character is encountered: the delimiting character being either the newline character ('\n') or delim (if this argument is specified).
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.


So your code is behaving as expected.

Extracting the newline char should work

1
2
3
4
5
6
7
   char abc[20];
   std::cin.get(abc,20);
    
   char nl; // now a char
   std::cin.get(nl);
  
   std::cout<<"|"<<nl<<"|";


Andy
Last edited on
Topic archived. No new replies allowed.