C++ getline()的两种用法

getline():用于读入一整行的数据。在C++中,有两种getline函数。第一种定义在头文件<istream>中,是istream类的成员函数;第二种定义在头文件<string>中,是普通函数。

第一种: 在<istream>中的getline()函数有两种重载形式:

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

作用是: 从istream中读取至多n个字符(包含结束标记符)保存在s对应的数组中。即使还没读够n个字符,如果遇到delim标识符或字数达到限制,则读取终止。delim标识符会被读取,但是不会被保存进s对应的数组中。注意,delim标识符在指定最大字符数n的时候才有效。

#include <iostream>
using namespace std;

int main()
{
    char name[256], wolds[256];
    cout<<"Input your name: ";
    cin.getline(name,256);
    cout<<name<<endl;
    cout<<"Input your wolds: ";
    cin.getline(wolds,256,',');
    cout<<wolds<<endl;
    cin.getline(wolds,256,',');
    cout<<wolds<<endl;
    return 0;
}

输入

Kevin
Hi,Kevin,morning

输出

Kevin
Hi
Kevin

第二种: 在<string>中的getline函数有四种重载形式:

istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);

用法和上第一种类似,但是读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。

is:表示一个输入流,例如cin。

str:string类型的引用,用来存储输入流中的流信息。

delim:char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到’ ’,则终止输入。

#include<iostream>
#include<string>
using namespace std;
int main(){
    string str;
    getline(cin, str, 'A');
    cout<<"The string we have gotten is :"<<str<<'.'<<endl;
    getline(cin, str, 'B');
    cout<<"The string we have gotten is :"<<str<<'.'<<endl;
return 0;}

输入

i_am_A_student_from_Beijing

输出

The string we have gotten is :i_am_.
The string we have gotten is :_student_from_.
原文地址:https://www.cnblogs.com/yun-an/p/11458060.html