c++当中的istringstream 和 ostringstream

      在编码过程中经常与输入设备打交道,特别是进入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;
}

 

发布了157 篇原创文章 · 获赞 98 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43447989/article/details/102654581
今日推荐