当迭代字符串时,Stringstream不起作用

Stringstream when iterating through string doesnt work

本文关键字:Stringstream 不起作用 迭代 字符串      更新时间:2023-10-16

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

假设一切都是用:

 using namespace std;

当我这样做时,一个基本的情况似乎是有效的:

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

然而,假设我有一个字符串定义为:

string test = "1234567891";

and I do:

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;

您需要的是:

#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。如果需要将ASCII c转换为它所表示的整数,则从中减去'0',如int i = c - '0';

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

for(char c: str)
{
    int i = c - '0';
    std::cout << i << std::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
}