C++中关于getline()和cin.getline()的使用

getline()和cin.getline()是C++中用于获取一整行输入的操作函数。

getline():

1、需要包含头文件 string
2、参数1为标准输入源 cin
3、参数2为字符串变量

string str;
getline(cin, str);

cin.getline()

1、可以看做是cin的成员函数
2、参数1是字符数组的头指针
3、参数2是需要读取的字符长度,包含末尾的换行符

char c[10];
cin.getline(c, 5);

关于getline()的使用示例:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    
    string str;
    getline(cin, str);
    cout << str << endl;
    return 0;
}

关于cin.getline()的使用示例:

#include <iostream>
using namespace std;

int main()
{
    
    
    char c[10];
    /*
        cin.getline();
        参数1:字符数组的头指针
        参数2: 要读取的字符数量,包含换行符
    */
    cin.getline(c, 5);

    /*
        输入:123456
        输出:1234
    */
    cout << c << endl;
    
    return 0;
}

谢谢阅读

猜你喜欢

转载自blog.csdn.net/weixin_43869898/article/details/108284185