stringstream string to int [英] stringstream string to int

查看:196
本文介绍了stringstream string to int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的C ++代码 int string int string string int 然后,它再次重复这些步骤。 stringstream int stream1> i3; 是打破代码。我在这里缺少什么?

The C++ code below does int to string, int to string and a string to int conversions. Then, it repeats these steps again. The stringstream to int line stream1 >> i3; is breaking the code. What am I missing here?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
 int i1 = 101;
 int i2 = 202;
 int i3 = 0;
 string s1 = "";
 string s2 = "";
 stringstream stream1;

 for (int i=0;i<2;i++)
 {

   //int to string
   stream1.str("");
   cout << "i1 " << i1 << endl;
   stream1 << i1;
   s1 = stream1.str();
   cout << "s1 " << s1 << endl;

   //int to string
   cout << "i2 " << i2 << endl;
   stream1.str("");
   stream1 << i2;
   s2 = stream1.str();
   cout << "s2 " << s2 << endl;

   //string to int
   stream1.str("");
   stream1.str(s2);
   stream1 >> i3;
   //line above causes s1 and s2 to get messed up during 2nd time in for loop
   cout << "i3-- " << i3 << endl;

  }
  return 0;
 }


推荐答案

再现问题。我解决了在.str()之前插入一个.clear()

I tested your code and could reproduce the problem. I solved it inserting a .clear() before .str("")

看看这里:如何重用ostringstream?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
 int i1 = 101;
 int i2 = 202;
 int i3 = 0;
 string s1 = "";
 string s2 = "";
 stringstream stream1;

 for (int i=0;i<2;i++)
 {

   //int to string
   stream1.clear();
   stream1.str("");
   cout << "i1 " << i1 << endl;
   stream1 << i1;
   s1 = stream1.str();
   cout << "s1 " << s1 << endl;

   //int to string
   cout << "i2 " << i2 << endl;
   stream1.clear();
   stream1.str("");
   stream1 << i2;
   s2 = stream1.str();
   cout << "s2 " << s2 << endl;

   //string to int
   stream1.clear();
   stream1.str("");
   stream1.str(s2);
   stream1 >> i3;
   //line above causes s1 and s2 to get messed up during 2nd time in for loop
   cout << "i3-- " << i3 << endl;

  }
  return 0;
 }

这篇关于stringstream string to int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆