-2

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 :

getlinereads 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 :(

ryanpattison
  • 5,841
  • 1
  • 18
  • 28
pastram
  • 3
  • 1
  • See [`std::istream::get()`](http://en.cppreference.com/w/cpp/io/basic_istream/get) and [`std::istream::getline()`](http://en.cppreference.com/w/cpp/io/basic_istream/getline) for clarification please. – πάντα ῥεῖ Feb 17 '15 at 17:11

2 Answers2

-1

"get" only retrieves a character, "getline" gets all characters to a line terminator. Thats the main difference.

AngularLover
  • 364
  • 1
  • 12
  • 1
    `get` has an overload that reads to a line terminator. I guess that's what OP is asking about. – interjay Feb 17 '15 at 17:11
  • I believe the OP is asking about [#4](http://en.cppreference.com/w/cpp/io/basic_istream/get) vs. [#2](http://en.cppreference.com/w/cpp/io/basic_istream/getline). – chris Feb 17 '15 at 17:12
-1

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 .

tmlen
  • 7,586
  • 3
  • 28
  • 65