文章目录
getline
头文件 cstring
getline() 会把进行cin输入时行末丢弃的换行符读入,从而造成getline()第一次获得的数据为一空行
需要插入
cin.ignore();
#include <iostream>
using namespace std;
int main(){
string str;
int t;
cin >> t;
cin.ignore();
getline(cin,str);
cout << t << str << endl;
return 0;
}
stringstream
#include <iostream>
#include <sstream>
using namespace std;
int main(){
stringstream ss;
ss << "str1" << " " << "str2";
ss << 123;
cout << ss.str() << endl;
return 0;
}

#include <iostream>
#include <sstream>
using namespace std;
int main(){
string str,x;
getline(cin,str);
stringstream ss(str);
cout << ss.str() << endl;
while(ss >> x){
cout << x << endl;
}
return 0;
}

本文详细介绍了C++中用于处理字符串的两个重要工具:getline和stringstream。通过实例展示了如何使用getline从输入流中读取整行,以及如何利用stringstream进行字符串流操作,包括插入和提取数据。同时,提到了使用getline时需要注意的cin.ignore()的使用,以避免丢失换行符。文章最后演示了如何结合stringstream进行字符串的解析和输出。
918

被折叠的 条评论
为什么被折叠?



