c++中getline()函数用法与坑

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

我们看一下官网介绍:
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ‘\n’, for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

Note that any content in str before the call is replaced by the newly extracted sequence.

Each extracted character is appended to the string as if its member push_back was called.

有两种函数原型,下面是上面delim=‘\n’的一种特殊情况,delim是分隔符。读取到分隔符结束,并把分隔符从流中丢弃。有两种情况会停止读取,1是遇到分隔符,2是文件结束。

常见错误

我们有时候可能会遇到读不到东西,像下面这种,我们输入3然后回车程序直接结束了,而不是我们以为的会接着等待输入。理解这个问题,请你想象一条字符流,cin>>a将流中的整数取走了剩下了\ngetline发现了截止符,终止输入导致a为空。

    string a;
    int b;
    cin>>b;
    getline(cin,a);
    cout<<a;
用法

c++中没有split方法,用下面代码可以模拟split。

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

int main(){
    string date;
    cin>>date;
    stringstream ss(date);
    string t;
    while(getline(ss,t,'/')){
        cout<<t<<endl;
    }
}
/*
输入:
	02/03/04
输出:
	02
	03
	04
*/

参考:
http://www.cplusplus.com/reference/string/string/getline/

posted @ 2019-02-28 18:48  开局一把刀  阅读(5)  评论(0)    收藏  举报