Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cin.getline( ) vs. std::cin

Tags:

c++

getline

cin

When should std::cin.getline() be used? What does it differ from std::cin?

like image 533
Simplicity Avatar asked Jan 20 '11 10:01

Simplicity


People also ask

What is CIN Getline in C++?

The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input. That's where the getline() function comes in handy.

What is std :: getline?

std::getline (string)Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).

What is difference between getline () and read () function?

getline by comparison will pull the delimiter off the stream, but then drop it. It won't be added to the buffer it fills. get looks for \n , and when a specific number of characters is provided in an argument (say, count ) it will read up to count - 1 characters before stopping. read will pull in all count of them.

Can you use Cin and Getline together?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.


1 Answers

Let's take std::cin.getline() apart. First, there's std::. This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.

std::cin is such an object. It's the standard character input object, defined in <iostream>. It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.

Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side (std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases: 1. The end of a line is reached 2. There are no characters left in the input (doesn't happen normally on std::cin as you can keep typing) 3. The maximum number of characters is read.

There are other methods and functions that can be used with the std::cin object, e.g.

  std::string s;   int i;   std::cin >> s; // Read a single word from std::cin   std::cin >> i; // Read a single number from std::cin   std::getline(std::cin, s); // Read an entire line (up to \n) from std::cin   std::cin.ignore(100); // Ignore the next 100 characters of std::cin 
like image 102
MSalters Avatar answered Sep 23 '22 17:09

MSalters