Original article:
Http://www.wutianqi.com /? P = 1181
When learning C ++ programming, we generally use cin in terms of input.
Cin uses spaces (spaces, tabs, and line breaks) to define the bounds of strings.
This causesString with spacesFor example, "I Love C ++ struggle paradise Forum"
Only "I" can be read.
What should I do?
1. For character Arrays:
Method 1: getline ()
Reads the entire row of data. It uses the line break entered by the Enter key to determine the end of the input.
Call method: cin. getline (str, len );
The first parameter 'str' is used to store the name of the array in the input line, and the second parameter 'len' is the number of characters to read.
1 # include <iostream>
2 using namespace std;
3
4 int main ()
5 {
6 char str [30];
7 cin. getline (str, 30 );
8 cout <str <endl;
9 return 0;
10}
Method 2: get ()
Call method: cin. get (str, len );
1 # include <iostream>
2 using namespace std;
3
4 int main ()
5 {
6 char str [30];
7 cin. get (str, 30 );
8 cout <str <endl;
9 return 0;
10}
So what is the difference between the two?
Both read a line of input until the line break.
Then,Getline discards the linefeed, while get () retains the linefeed in the input sequence..
Therefore, when using cin. get () to input multiple rows of data, you can use get () to eliminate line breaks.
1 # include <iostream>
2 using namespace std;
3
4 int main ()
5 {
6 char str1 [30], str2 [30];
7 cin. get (str1, 30 );
8 cin. get ();
9 cin. get (str2, 30 );
10 cout <"str1:" <str1 <endl;
11 cout <"str2:" <str2 <endl;
12 return 0;
13}
Because get (str, len) and get () are both members of the cin class, they can be combined to write:
1 # include <iostream>
2 using namespace std;
3
4 int main ()
5 {
6 char str1 [30], str2 [30];
7 cin. get (str1, 30). get (); // pay attention to this!
8 cin. get (str2, 30 );
9 cout <"str1:" <str1 <endl;
10 cout <"str2:" <str2 <endl;
11 return 0;
12}
(Welcome to my forum for study: C ++ struggle Park: www. cppleyuan (dot) com)
2. For the string class
Method 1: getline (cin, str)
This indicates that getline is not a class method.
1 # include <iostream>
2 # include <string>
3 using namespace std;
4
5 int main ()
6 {
7 string str;
8 getline (cin, str );
9 cout <str <endl;
10 return 0;
11}
PS: If you want to know more about input in the future, we will continue to add more information. I hope you can support it and have more exchanges.