#include<iostream>
using namespace std;
#include<string>
#include<sstream>
int main(){
int Np, Nn;
cout<<"input a line: "<<endl;
string line; getline(cin, line);
stringstream strm( line );
strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<" Nn = "<<Nn<<endl;
return 0;
}
~
运行结果:
luyi@Swagger:~/test/getline$ g++ getline.cpp; ./a.out input a line: 3 5 7 sadfa zxcv Np = 3 Nn = 5
可以看到,输入了" 3 5 7 sadfa zxcv"一整行,然后把行首第一个非空格的数字赋给了Np, 第二个赋给了Nn。
也可以提取行首字符串,也是从第一个非零的字符开始:#include<iostream>using namespace std;
#include<string> #include<sstream> int main(){ int Np, Nn; cout<<"input a line: "<<endl; string line; getline(cin, line); stringstream strm( line ); string name; strm>>name; cout<<"name ="<<name<<endl; strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<" Nn = "<<Nn<<endl;
return 0; } ~
运行结果:
luyi@Swagger:~/test/getline$ g++ getline.cpp ; ./a.out input a line: Jerry 3 5 2342 name =Jerry Np = 3 Nn = 5
也可以再次给 strm 内容赋值,使用 strm.str( string ),但是 strm 第二次使用的时候,一定要先clear,否则可能会出错(亲测)。
以下是正确代码
#include<iostream> using namespace std; #include<string> #include<sstream> int main(){ int Np, Nn; cout<<"input a line: "<<endl; string line; getline(cin, line); stringstream strm( line ); string name; strm>>name; cout<<"name ="<<name<<endl; strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<" Nn = "<<Nn<<endl; string newname; cout<<"input a new name: "; getline(cin, line); strm.clear(); strm.str(line); strm>>newname; cout<<"new name="<<newname<<endl; return 0; } ~
如果不写中间的 strm.clear(); 有时不出错,有时出错,所以是不可靠的。