字符串流和格式
我正在使用 C++ 编写一个程序,该程序应该用素数做很多事情。然而,主要问题是我在整数和字符串之间转换时遇到问题。我相信以下是相关代码:
for(int j=0;j<size-1;j++){
num=primes[j];
ss<<num;
ss>>temp;
ss.str("");
for (int count=0; count < temp.size(); count++) {
cout<<temp<<endl;
}
我知道我可以谷歌并找出如何以另一种方式从整数转换。然而,我有一种感觉,我无法弄清楚出了什么问题的原因是因为我缺乏一些关于字符串流的基本知识,我不知道这些知识我希望能够得到修复。 num
是一个 int,ss
是一个字符串流,cout temp
每次都会打印出 2,这是 primes 的值[0]
。我认为字符串流可能在第一次试验后无法读取,因为与换行符有关,但我真的不知道。
I am using C++ and writing a program that is supposed to do a bunch of stuff with primes. However the main issue is that I am having trouble converting in between ints and strings. I believe the following is the relevant code:
for(int j=0;j<size-1;j++){
num=primes[j];
ss<<num;
ss>>temp;
ss.str("");
for (int count=0; count < temp.size(); count++) {
cout<<temp<<endl;
}
I know that I could Google and figure out how to convert from an integer another way. However, I have a feeling that the reason I can't figure out what is going wrong is because I'm lacking some fundamental knowledge about stringstreams which I'm not aware of which I'm hoping can be fixed. num
is an int and ss
is a stringstream and cout temp
is printing out 2 every single time, which is the value of primes[0]
. I think the stringstream might be not reading after the first trial because of something to do with a newline character but I don't really know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到这种情况的原因是,在将第一个值读入
temp
后,EOF_BIT 将在ss
中设置,此后无法对ss
进行读/写操作。 code>std::stringstream,因此temp
不会用新值更新。以更易于理解的方式解释上述内容; std::stringstream
ss
会认为它已经到达末尾(在某一时刻它已经到达末尾)。您需要告诉它“重新开始”(重置所有错误标志),以便它可以在另一次迭代中使用。我该如何解决这个问题?
有几种可用的方法,对我来说最清楚的(在代码可读性方面)是为循环中的每个迭代器使用新的
std::stringstream
(请参阅“示例解决方案 #2< /strong>)。查看下面所有将输出的代码片段:
示例解决方案#1
示例解决方案#2
示例解决方案#3
The reason for what you are experiencing is that the EOF_BIT will be set in
ss
after reading the first value intotemp
, after that no read/writes can be made to thestd::stringstream
and thereforetemp
is not updated with a new value.A more human readable way of explaining the above; the std::stringstream
ss
will think that it has reached the end (which it has, at one point). You'll need to tell it to "start all over again" (reset all error-flags) for it to be usable in another iteration.How do I solve this issue?
There are a few methods available, to me the most clear (in code readability) is to use a new
std::stringstream
for each iterator in your loop (see "Example solution #2).Check out the snippets below that all will output:
Example solution #1
Example solution #2
Example solution #3