使用 Stringstream 将字符串转换为 Int
这里有一个小问题:
int IntegerTransformer::transformFrom(std::string string){
stream->clear();
std::cout<<string<<std::endl;;
(*stream)<<string;
int i;
(*stream)>>i;
std::cout<<i<<std::endl;
return i;
}
我通过使用字符串“67”调用这个函数(其他值也不起作用)我得到这个输出:
67
6767
have a little problem here:
int IntegerTransformer::transformFrom(std::string string){
stream->clear();
std::cout<<string<<std::endl;;
(*stream)<<string;
int i;
(*stream)>>i;
std::cout<<i<<std::endl;
return i;
}
I by calling this function with the string "67" (other values dont work too) i get this output:
67
6767
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否注意到函数本身有两个
std::cout
?除此之外还添加以下内容:
顺便说一下,为什么不使用boost::lexical_cast?
Did you notice there are two
std::cout
in the function itself?Beside that also add this:
By the way, why don't you use
boost::lexical_cast
?这不会“清空”字符串流的内容。它会重置从流读取失败时设置的错误标志(例如,因为文本的格式不正确,无法读取整数)。
处理这个问题的最简单方法是创建一个新的、本地作用域的字符串流:
请注意,您也不再需要搞乱指针(并且我假设是动态分配),并且您可以只使用构造函数设置初始值。
一般来说,将流作为类的数据成员是一个坏主意。它们确实不适合这种用途。
下一个最简单的解决方案是使用实际用于该作业的成员函数
.str()
,如 Nawaz 所示。正如 Nawaz 所提到的,放弃整个事情并仅使用
boost::lexical_cast
无论如何可能是一个更好的主意。不要重新发明轮子。This does not "empty out" the stringstream's contents. It resets the error flags that get set when reading from the stream fails (e.g. because the text is not in the right format to read an integer).
The simplest way to deal with this is to just create a new, locally scoped stringstream:
Notice how you also no longer have to mess around with pointers (and, I'm assuming, dynamic allocation), and that you can just use the constructor to set the initial value.
Having streams as data members of a class is a bad idea in general. They really aren't meant for that kind of use.
The next easiest solution is to use the member function that's actually intended for the job,
.str()
, as shown by Nawaz.As also mentioned by Nawaz, scrapping the whole thing and just using
boost::lexical_cast
is probably a better idea anyway. Don't reinvent the wheel.