Get the entire line of user input string input in c++

Get the user's entire line of string input in c++

There are three methods to obtain the entire line of user input in C++, namely:

  1. cin.getline(str, len);

示例:
char str[30];
cin.getline(str, 30);
cout << str << endl;

  1. cin.get(str, len);

char str[30];
cin.get(str, 30);
cout << str << endl;

  1. getline(cin, str);

string str;
getline(cin, str);
cout << str << endl;

Example of method three:

#include<iostream>
#include <string>

using namespace std;

int main() {
    
    

    string name;
    cout << "enter your name " << endl ;
    getline(cin,name);
    cout << "your name is " << name << endl;

    int age;
    cout << "enter your age:" << endl;
    cin >> age;
    cout << "you are " << age << " years old" << endl;

    char grade;
    cout << "enter your grade" << endl;
    cin >> grade;
    cout << "your grade is " << grade << endl;

    string adress;
    cout << "enter your adress " << endl ;
    getline(cin,adress);
    getline(cin,adress);
    cout << "your adress is " << name << endl;

    cout << "Hello" << name <<  " you are " << age << " years old " << " your grade is " << grade << endl;
    
    return 0;

}

In the above code, the user input format is obtained and printed in the form of integer, character, and string. When using getline() to obtain the entire line of string input, it is used twice because the first time it is read The line break of the last user input is recognized as the end character and needs to be used twice to obtain user input. This situation will not occur if it is placed at the beginning of the code to obtain it. This situation also exists in the second method cin.get().

Reference blog: http://t.csdn.cn/iv8ZF
http://www.wutianqi.com/blog/1181.html

Guess you like

Origin blog.csdn.net/balabala_333/article/details/131933778