C ++ getline function uses Detailed

Although you can use cin >> and operator to input string, but it can cause some problems that need attention.

Cin When reading data, and transmitting it ignores any leading white space characters (space, tab or newline). Once it touches the first non-space character begins to read, when it is read to the next blank character, it will stop reading. For example in the following statement:

cin >> namel;

Enter "Mark" or "Twain", but can not enter the "Mark Twain", because the input cin not contain the string embedded spaces. The following program demonstrates the problem:
    
    
  1. // This program illustrates a problem that can occur if
  2. // cin is used to read character data into a string object.
  3. #include <iostream>
  4. #include <string> // Header file needed to use string objects
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string name;
  10. string city;
  11. cout << "Please enter your name: ";
  12. cin >> name;
  13. cout << "Enter the city you live in: ";
  14. cin >> city;
  15. cout << "Hello, " << name << endl;
  16. cout << "You live in " << city << endl;
  17. return 0;
  18. }
Program output:

Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe

Note that in this example, the user no chance to enter the city city name. Because the first input statement, when read cin space between John and Doe, it will stop reading, just as the value stored in John's name. In the second input sentence, using the remaining characters in the keyboard buffer CIN found and Doe as the value stored in the city.

To solve this problem, you can use called getline the C ++ function. This function reads the entire line, including the leading and embedded spaces, and stored in a String object.

getline function as follows:

getline(cin, inputLine);

Where cin is the input stream is being read, the string variable name inputLine received input string. The following program demonstrates the use of the getline function:
    
    
  1. // This program illustrates using the getline function
  2. //to read character data into a string object.
  3. #include <iostream>
  4. #include <string> // Header file needed to use string objects
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string name;
  10. string city;
  11. cout << "Please enter your name: ";
  12. getline(cin, name);
  13. cout << "Enter the city you live in: ";
  14. getline(cin, city);
  15. cout << "Hello, " << name << endl;
  16. cout << "You live in " << city << endl;
  17. return 0;
  18. }
Program output:

Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago

Guess you like

Origin www.cnblogs.com/xjyxp/p/11546060.html