c++ - 遍历字符串时 Stringstream 不起作用

标签 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;

最佳答案

有两点你应该明白。

  1. 如果您使用索引访问字符串,您将获得字符。
  2. istringstream 需要 string 作为参数而不是字符来创建对象。

现在你在你的代码中

    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
}

关于c++ - 遍历字符串时 Stringstream 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072683/

相关文章:

java - 具有多个字符串参数的 Bash 脚本

sql - Spring 启动和 hibernate : update all column's rows where entry is null

c++ - 防止继承 operator new 和 delete

c++ - 在这里显式调用析构函数会导致未定义的行为吗?

c#将表达式中的字符串转换为int

string - 如何转义 bash printf 中的一系列反斜杠?

javascript - 更改 JavaScript 中 forEach 循环的每次迭代的颜色?

javascript - for循环中的延迟

c++ - 使用 FreeType 库创建文本位图以在 OpenGL 3.x 中绘制

c++ - 调试断言失败 : _CrtIsValidHeapPointer(block)