c++中获取用户输入之整行字符串输入

c++中获取用户整行字符串输入

在c++中获取用户整行输入时有3种方法,分别是:

  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;

方法三示例:

#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;

}

在以上代码中,实现了对用户输入格式为整型、字符型、字符串型进行获取并打印,在使用getline()获取整行字符串输入时,用了两次,因为第一次读取了上一次用户输入的换行,识别为结束符,需要二次使用获取用户输入,如果放在代码开始位置进行获取则不会出现该情况。在第二种方法cin.get()中,也存在该情况。

参考博客:http://t.csdn.cn/iv8ZF
http://www.wutianqi.com/blog/1181.html

猜你喜欢

转载自blog.csdn.net/balabala_333/article/details/131933778
今日推荐