迭代字符串时的Stringstream不起作用

时间:2015-10-12 03:08:27

标签: c++ string loops iostream sstream

所以我想使用字符串流将字符串转换为整数。

假设一切都完成了:

 using namespace std;

一个似乎有用的基本案例就是当我这样做时:

 string str = "12345";
 istringstream ss(str);
 int i;
 ss >> i;

工作正常。

但是我可以说我有一个字符串定义为:

string test = "1234567891";

我做了:

int iterate = 0;
while (iterate):
    istringstream ss(test[iterate]);
    int i;
    ss >> i;
    i++;

这并不像我想的那样工作。本质上我是在对字符串的每个元素进行单独处理,就好像它是一个数字,所以我想先将它转换为int,但我似乎也不能。有人可以帮助我吗?

我得到的错误是:

   In file included from /usr/include/c++/4.8/iostream:40:0,
             from validate.cc:1:
/usr/include/c++/4.8/istream:872:5: note: template<class _CharT, class _Traits, class _Tp> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&)
 operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
 ^
/usr/include/c++/4.8/istream:872:5: note:   template argument     deduction/substitution failed:
validate.cc:39:12: note:   ‘std::ostream {aka std::basic_ostream<char>}’ is not derived from ‘std::basic_istream<_CharT, _Traits>’
cout >> i >> endl;

2 个答案:

答案 0 :(得分:1)

您需要的是:

#include <iostream>
#include <sstream>

int main()
{
    std::string str = "12345";
    std::stringstream ss(str);
    char c; // read chars
    while(ss >> c) // now we iterate over the stringstream, char by char
    {
        std::cout << c << std::endl;
        int i =  c - '0'; // gets you the integer represented by the ASCII code of i
        std::cout << i << std::endl;
    }
}

Live on Coliru

如果您使用int c;代替c类型,则ss >> c会读取整个12345整数,而不是char char 1}}。如果您需要将ASCII c转换为它所代表的整数,请从中减去'0',例如int i = c - '0';

编辑正如评论中提到的@dreamlax一样,如果您只想读取字符串中的字符并将其转换为整数,则无需使用stringstream。您可以将初始字符串迭代为

for(char c: str)
{
    int i = c - '0';
    std::cout << i << std::endl;
}

答案 1 :(得分:1)

您应该了解两点。

  1. 如果使用索引访问字符串,则会获得字符。
  2. istringstream需要string作为参数而非要创建对象的字符。
  3. 现在你的代码

        int iterate = 0;
         while (iterate):
        /* here you are trying to construct istringstream object using  
     which is the error you are getting*/
            istringstream ss(test[iterate]); 
            int i;
            ss >> i;
    

    要解决此问题,您可以按照方法

    istringstream ss(str); 
    int i;
    while(ss>>i)
    {
        std::cout<<i<<endl
    }