当迭代字符串时,Stringstream不起作用
Stringstream when iterating through string doesnt work
所以我想使用字符串流将字符串转换为整数。
假设一切都是用:
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;
}
有两点你应该明白。
- 如果你使用索引访问字符串,你将得到字符。
-
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
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- StringStream的Str方法将不起作用.(不同类型的串联)(C )
- Stringstream Noshowpoint 不起作用
- Visual Studio std::stringstream pubsetbuf 不起作用
- QByteArray to QString to std::stringstream 不起作用
- 当迭代字符串时,Stringstream不起作用