【问题标题】:Stringstream when iterating through string doesnt work遍历字符串时的Stringstream不起作用
【发布时间】:2016-01-09 10:24:51
【问题描述】:

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

假设一切都完成了:

 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;

【问题讨论】:

  • 在没有分隔符的情况下,您希望流如何识别将字符串分解为单个元素的位置?
  • 如果您使用的是 test[iterate] 那么您有一个包含数字的 ASCII 字符。要将包含数字的 ASCII 字符转换为数字,您只需减去“0”。 int i = test[iteratet] - '0'

标签: c++ string loops iostream sstream


【解决方案1】:

有两点你应该明白。

  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
}

【讨论】:

    【解决方案2】:

    你需要的是这样的:

    #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 &gt;&gt; c 读取整个整数12345,而不是通过char 读取它char。如果您需要将 ASCII c 转换为它所代表的整数,请从中减去 '0',例如 int i = c - '0';

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

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

    【讨论】:

    • 如果您只是要遍历字符串中的各个字符,那么使用字符串流是没有意义的。也可以使用迭代器迭代字符串。 for (char c : str) std::cout &lt;&lt; (c - '0');
    • @dreamlax 没错,我想我写上面的 sn-p 只是为了展示 stringstream 的工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2018-05-15
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多