getline
Syntax:
#include <string> istream& getline( istream& is, string& s, char delimiter = '\n' );
getline是读一行 遇到换行符才结束
istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。 (以空格分隔提取字符)
举个例子
来自cppprefence
// expects either space-delimited numbers or lines that start with // two forward slashes (//)#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string s; while( getline(cin,s) )
{ if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) { cout << " ignoring comment: " << s << endl; } else { istringstream ss(s); double d; while( ss >> d ) { cout << " got a number: " << d << endl; } } }
When run with a user supplying input, the above code might produce this output:输入如下字符: // test 回车
ignoring comment: // test 23.3 -1 3.14159
got a number: 23.3
got a number: -1
got a number: 3.14159
// next batch
ignoring comment: // next batch
1 2 3 4 5 got a number: 1 got a number: 2 got a number: 3 got a number: 4 got a number: 5 50 got a number: 50
可以看到getline 读一行 istringstream 按空格分别读进s。