C++ [How to input a string with spaces]

One, the problem

When encountering string algorithm problems, there is often such a situation:

Define a string a,

If we want a = "hello world",

There are spaces in this string,

However, it cannot satisfy the two most commonly used inputs:

1. Cin is the most commonly used input sentence in C++, but when it encounters a space or enter key, the input stream stops.

2. The general format of scanf function is scanf("%s",st), but scanf default carriage return and space is the interval and end symbol between input different groups, so inputting a string with spaces, tabs or carriage returns is not It is possible.

Two, the solution 

getline() (include header file #include <string>)

More commonly used.

If the variable is defined as a string type , the getline() function must be considered. The usage is as follows:

string a;
getline(cin, a);

 

Guess you like

Origin blog.csdn.net/Kukeoo/article/details/114326822