-2

I'm running a few tests by playing around with the member functions of C++ and I'm confused on why sometimes get() doesn't read a new-line character. I've used a do-while loop to test and it seems to work that way, but not with a traditional if-else statement.

Let's say input is The\n.

#include <iostream>
using namespace std;

int main()
{
   char test;
    
    cin.get(test);
    cin.get(test);
    cin.get(test);
    cin.get(test);
   
    
    if (test == '\n')
    {
        cout << "Test successful!";
    }
   
}

It doesn't seem to read '\n' at all. Is there something I'm not getting here?

Austin
  • 2,203
  • 3
  • 12
  • 28
  • 2
    `cin.get()` reads up to a delimiter, but doesn't include it. The default delimiter is the newline character. – h0r53 Aug 22 '23 at 18:51
  • 1
    It prints `Test successful!` on my Linux box with the input you've given. It also does at godbolt.org: [Demo](https://godbolt.org/z/s5Wvcjv76) – Ted Lyngmo Aug 22 '23 at 18:51
  • 1
    @h0r53 No, that's if you use overload with delimiter. This code uses [overload 1](https://en.cppreference.com/w/cpp/io/basic_istream/get), which reads exactly one character, whatever it is – Yksisarvinen Aug 22 '23 at 18:52
  • 2
    @OP Are you on Windows? Newline on Windows is represented with two characters: `\r` and `\n`. – Yksisarvinen Aug 22 '23 at 18:53
  • What @Yksisarvinen asked is probably the answer. Print the numeric values of all the characters you read: `std::cout << static_cast(test) << '\n';` and you'll probably see a `13` (`\r`) before a `10` (`\n`) in an ASCII environment. [Example](https://godbolt.org/z/7fPdfv4GY) – Ted Lyngmo Aug 22 '23 at 19:02
  • My understanding is that `'\n'` is ASCII linefeed, hex 0x0A. The `'\r'` is ASCII carriage return. Some operating systems will treat a linefeed character as a new line (carriage return and linefeed). Other systems will treat a linefeed by going to the next line without changing the horizontal position. In summary, `'\n'` will always have the value 0x0A, but the behavior depends on the operating system and the terminal. See DEC Vt52 and VT100 standards, as well as Teletypes. See also *inix operating systems as well as other OSes. – Thomas Matthews Aug 22 '23 at 20:21

0 Answers0