Some important factors to know before the explanation:
- getline() reads input until the delimiter (default delimiter is the newline (“\n”)) character is found.
- getline removes the delimiter from the input buffer, std::cin or scanf does not.
- cin discards any other character present on the input buffer and takes the input only as new in the input buffer. That’s why while using cin after another cin, even when the previous cin leaves a newline in the input buffer, the later cin doesn’t get bothered with that.
So when a user takes any input using std::cin/ scanf(), they hit enter, which is actually a ‘\n’ char. cin leaves this “\n” in the input buffer. Then if you use getline, getline will only read that “\n” in the input buffer (instead of the string you want) and skip to next line. So the program seems to skip over the whole getline() command since newline (‘\n’) is the by-default delimiter for getline() and it immediately stops taking any more characters as input (alongside removing the delimiter itself from the input buffer).
So to solve this problem, we use getchar() or std::cin.ignore(1000,’\n’).
- getchar(): Before using getline(),The getchar() is used to read the character(after using cin/scanf) which is a “new line” (“\n”) and which wasn’t removed from the input-buffer by the cin/scanf.
- cin.ignore(100,’\n’): We use cin.ignore(100,’\n’) to clear the buffer up to the string that you want. In this syntax, The “1000” means to skip over a specific number of chars(in this case 100 chars) before the specified delimiter(in this case, the newline character)
4 thoughts on “Why we must use getchar() immediately before using getline() if std::cin or scanf() statements are present before the getline():”