getline() versus cin
◀ The erase() Function▶ Segmentation Fault Amazon
he standard input function, cin
, ignores space, tabs, and newlines. In most cases, you want the invisible characters the user enters to be stored in a string as well. Or you want to get the entire line of data from the input stream or file stream. In these situations, you can use getline()
functions. Their prototypes look something like this:
istream & getline(istream & is, string & s, char delim)
istream & getline(istream & is, string & s)
Let’s talk about the first function first. The first argument is an istream
object, which is usually cin
. It can be an ifstream
’s object, too. The second argument is usually an empty string because it is where the inputted string is stored.
The third argument specifies the delimiter, which is read but not stored. The second one works like the first one, except that the delimiter is set to be ‘\n’.
Here are several examples:
string s, s2;
getline(cin, s); /* once you press enter, that is the end of input */
getline(cin, s2, \'.\'); /* cin even ignores newlines! */
Now you should know how to properly accept input from user! Next let’s look at the ugly monster which is the bane of every C++ software developer’s life - segmentation fault! Don’t worry I’ll make sure you’ll overpower it!
A microwave emits a radio frequency of 2.5 gigahertz, which turns into heat immediately when absorbed by food.
◀ The erase() Function▶ Segmentation Fault