在編碼過程中經常與輸入設備打交道,特別是進入c++階段有了string類的幫助大大方便了字符串的處理。但是又遇到了新的問題,當cin遇到空格之後就會停止讀取,但這往往不是我們期望的。並且有時我們需要藉助空格分開一下字符串單獨處理。
比如,我們需要做這樣一件事,輸入 3 6 7 11 將它存放進數組中,平是我們用的scanf("%s",&str)也是以空格來結束讀取。
那我們有什麼新的方法能夠只以換行符爲讀取結束標誌呢 當然有,那就是getline()。但是還是不能滿足我們以空格爲分隔號處理字符串的目的,接下來引入istringstream來達到目的。
istringstream的頭文件是<sstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
int n,val;
string strvalues;
strvalues = "125 320 512 750 333";
istringstream iss (strvalues,istringstream::in);
for (n=0; n<5; n++)
{
iss >> val;
cout << val*2 << endl;
}
return 0;
}
輸出 250 640 1024 1500 666
string line;
vector<int> arr;
getline(cin, line);
istringstream iss(line);
while (iss >> tmp)
{
arr.push_back(tmp);
mmax = max(mmax, tmp);
sum += tmp;
}
可以將輸入的數字按空格分隔,並且可以按照tmp的類型作相應的轉化。
接下來看ostringstream
// using ostringstream constructors.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
ostringstream oss(ostringstream::out);
oss << "This is a test\n";
cout << oss.str();
//cout << oss.str();
system("pause");
return 0;
}