I am learning c++, however, I can not understand what is the difference BTW:
std::cin.get();
and
std::cin.getline();
although;I know how to use each of them, but can't understand why there are two? I've read this explanation :
getline
reads the newline character then discard it; whereas.get()
reads it then leaves it in the input queue ..!! why each of them does what it does ?
sorry for bad English :(
std::cin.get()
, when called without parameters, reads one single character from input and returns it.
std::cin.getline(char* str, std::streamsize count)
reads one line of input and copies it into the buffer str
, followed by an extra null character to form a C-string. count
must be the size of that buffer, i.e. the maximal number of characters (plus the null byte) it can copy into it.
To read a line without caring about the buffer size it may be better to use std::getline
:
#include <string>
std::string line;
std::getline(std::cin, line);
Reads a line from cin
into line
.
See http://en.cppreference.com/w/cpp/io/basic_istream and http://en.cppreference.com/w/cpp/string/basic_string/getline .