473,326 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Strange problem of typecasting with stringstream

I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;

from = "2";
conv << from;
conv >to;

The first casting worked fine, but the second casting didn't work at
all.
conv.str() returned "1" after 'from = "2"; conv << from;' was executed.
Then I explicitly changed the buffer of conv, like this:

conv.str("1");
conv >to;

conv.str("2");
conv >to;

Still, the first casting worked perfectly, the second one failed, to ==
1.
I'm wondering I've terribly misunderstanding something, sorry if I'm
asking the obvious.

Oct 10 '06 #1
10 2578
<vi******@gmail.comwrote in message
news:11*********************@c28g2000cwb.googlegro ups.com...
>I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;

from = "2";
conv << from;
conv >to;

The first casting worked fine, but the second casting didn't work at
all.
conv.str() returned "1" after 'from = "2"; conv << from;' was executed.
Then I explicitly changed the buffer of conv, like this:

conv.str("1");
conv >to;

conv.str("2");
conv >to;

Still, the first casting worked perfectly, the second one failed, to ==
1.
I'm wondering I've terribly misunderstanding something, sorry if I'm
asking the obvious.
I"m suspecting that the stringstream is having "12" instead of "1 2" or
soemthing. I would try the following til I found what worked.

from = "1";
conv << from;
conv >to;

from = " 2";
conv << from;
conv >to;

if that didnt' work see what

from = "1 2";
conv << from;
conv >to;
conv >to;

gives you.

You may need to reset the stringstream in between, but I've never had that
problem.
Oct 10 '06 #2
vi******@gmail.com wrote:
I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;
Try:
conv.clear();
>
from = "2";
conv << from;
conv >to;
Regards,
Sumit.
Oct 10 '06 #3

Jim Langston wrote:
from = "1";
conv << from;
conv >to;

from = " 2";
conv << from;
conv >to;
didn't work.
from = " 2";
conv << from;
didn't change the inner buffer of conv, conv.str() still returned "1".
if that didnt' work see what

from = "1 2";
conv << from;
conv >to;
conv >to;
this worked.
gives you.

You may need to reset the stringstream in between, but I've never had that
problem.
Oct 10 '06 #4

Sumit Rajan wrote:
vi******@gmail.com wrote:
I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;

Try:
conv.clear();
yes, conv.clear() did the job, but why the previous method doesn't
work?
I've done some test, it seems that if conv's internal pointer ever
pointed to the end of its buffer, the next << operation would fail.
These code worked as intended:
conv << "1"; /* conv.str() = "1", conv.tellg() = 0 */
conv << " 2"; /* conv.str() = "1 2", conv.tellg() = 0 */
conv >to; /* conv.str() = "1 2", conv.tellg() = 1, to =
1*/
conv << " 3"; /* conv.str() = "1 2 3", conv.tellg() = 1 */
conv >to; /* conv.str() = "1 2 3", conv.tellg() = 3, to =
2 */
but these didn't
conv1 << "1"; /* conv.str() = "1", conv.tellg() = 0 */
conv1 << " 2"; /* conv.str() = "1 2", conv.tellg() = 0 */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = 1, to =
1 */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = 3, to =
2, internal pointer reached the end */
conv1 << " 3"; /* conv.str() = "1 2", conv.tellg() = -1, <<
operation failed */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = -1, to =
2 */
I did the test on MS Visual Studio .NET 2003, is this a bug of the
standard library implementation I'm using?
>

from = "2";
conv << from;
conv >to;

Regards,
Sumit.
Oct 10 '06 #5
vi******@gmail.com wrote:
I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:
Doesn't compile. Please post complete programs, see
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
>
stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;
So what do you think happens in the last line. To be like the library,
you have to think like the library :-) You read all characters upto and
including EOF. Thus setting state |= eofbit in conv. Thus making the
stream invalid for all further operations.
>
from = "2";
conv << from;
conv >to;
The << operator returns without doing anything, because your eofbit is
set. The >operator returns without doing anything, because the eofbit
is set.
conv.str() returned "1" after 'from = "2"; conv << from;' was executed.
Well, conv << from; was a NOP for the reasons mentioned. conv.str() is
"1" before you do nothing. It will still return "1" after you do
nothing.
Then I explicitly changed the buffer of conv, like this:

conv.str("1");
conv >to;

conv.str("2");
conv >to;

Still, the first casting worked perfectly, the second one failed, to ==
1.
There is no casting in your code. You probably have a scripting
language background, like perl. The terms we use in C++ for read
operations is something like "the first read". Casting is a different
concept and quite a subject in itself. Btw, if you take care not to
read EOF by adding a whitespace like " " or "\n", everything works
fine.

#include <sstream>
#include <iostream>

int main () {
std::stringstream conv("1\n");
int to;
conv >to;
std::cout << to << "\n";
conv.str("2\n");
conv >to;
std::cout << to << "\n";
}
I'm wondering I've terribly misunderstanding something, sorry if I'm
asking the obvious.
Your doing fine. You are just a little bit careless. And you should use
an IDE with a debugger. If you singlestep your program, the state
member of your stringstream will instantly tell you what's happend.

Oct 10 '06 #6

Gan Quan wrote in message
<11**********************@m7g2000cwm.googlegroups. com>...
>
Sumit Rajan wrote:
>vi******@gmail.com wrote:
I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;

Try:
conv.clear();
yes, conv.clear() did the job, but why the previous method doesn't
work?
I've done some test, it seems that if conv's internal pointer ever
pointed to the end of its buffer, the next << operation would fail.
These code worked as intended:
conv << "1"; /* conv.str() = "1", conv.tellg() = 0 */
conv << " 2"; /* conv.str() = "1 2", conv.tellg() = 0 */
conv >to; /* conv.str() = "1 2", conv.tellg() = 1, to =
1*/
conv << " 3"; /* conv.str() = "1 2 3", conv.tellg() = 1 */
conv >to; /* conv.str() = "1 2 3", conv.tellg() = 3, to =
2 */
but these didn't
conv1 << "1"; /* conv.str() = "1", conv.tellg() = 0 */
conv1 << " 2"; /* conv.str() = "1 2", conv.tellg() = 0 */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = 1, to =
1 */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = 3, to =
2, internal pointer reached the end */
conv1 << " 3"; /* conv.str() = "1 2", conv.tellg() = -1, <<
operation failed */
conv1 >to; /* conv.str() = "1 2", conv.tellg() = -1, to =
2 */
I did the test on MS Visual Studio .NET 2003, is this a bug of the
standard library implementation I'm using?
No, I don't think so. See my example below.

std::stringstream conv;
std::string from;
int to;

from = "1";
conv << from;
conv >to;
std::cout<<conv.str()<<" to="<<to<<std::endl;

// stringstream is now in a 'failed' state.... (sort of<G>)

from = "2";
conv << from;
conv >to;
std::cout<<conv.str()<<" to="<<to<<std::endl;

// ...so, trying to set it to "2" fails.

conv.clear(); // reset the stream to a 'good' state
from = "2";
conv << from;
conv >to;
std::cout<<conv.str()<<" to="<<to<<std::endl;

// see below

conv.str(""); // 'clear' the buffer
conv.clear(); // and 'reset' it.
from = "2";
conv << from;
conv >to;
std::cout<<conv.str()<<" to="<<to<<std::endl;
/* -- output --
1 to=1
1 to=1
12 to=2 // using only '.clear()'
2 to=2
*/

--
Bob R
POVrookie
Oct 10 '06 #7


BTW, if you do a whole bunch of string-to-number/number-to-string converting,
you may want these templates (put them in header file):
[ these were in a FAQ, but, I couldn't remember which one[1], so, I post
it.<G>]

#include <iostream>
// ------- any number to string, string to any number -------
#include <string>
#include<sstream>
#include <iomanip // for 'setprecision()'
template<typename TT FromString( std::string const &s){
std::istringstream is( s ); T t; is >t; return t;
} // FromString(string&)
template<typename Tstd::string ToString( T const &t, size_t prec = 6){
// std::ostringstream s; s << t; return s.str(); // original
std::ostringstream s;
s.setf(std::ios_base::fixed);
s <<std::setprecision( prec )<< t;
return s.str();
} // ToString(T&,size_t)
// ------------------------------------------------------

void TestPrint(){
using std::cout;
double Dnum(12345.6789);
std::string txt = ToString( Dnum );
double Dnum2 = FromString<double>( txt );
cout<<" ------- "<<std::endl;
cout<<" Dnum="<<Dnum<<std::endl;
cout<<" txt="<<txt<<std::endl;
cout<<" Dnum2="<<Dnum2<<std::endl;
cout<<" ------- "<<std::endl;
int Dnum3(12345);
txt = ToString( Dnum3 );
int Dnum4 = FromString<int>( txt );
cout<<" Dnum3="<<Dnum3<<std::endl;
cout<<" txt="<<txt<<std::endl;
cout<<" Dnum4="<<Dnum4<<std::endl;
cout<<" ------- "<<std::endl;
return;
} // TestPrint()

int main(){
TestPrint();
return 0;
} // main()
[1] - CRS and Sometimers!
--
Bob R
POVrookie
Oct 10 '06 #8
BobR schrieb:
>
BTW, if you do a whole bunch of string-to-number/number-to-string converting,
you may want these templates (put them in header file):
[ these were in a FAQ, but, I couldn't remember which one[1], so, I post
it.<G>]
[snipped code]

It's not the same code you posted, but it handles bad conversion:

From 39.1 to 39.3:
http://www.parashift.com/c++-faq-lit...al-issues.html

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Oct 10 '06 #9

Thomas J. Gritzan wrote in message ...
>BobR schrieb:
>>
BTW, if you do a whole bunch of string-to-number/number-to-string
converting,
>you may want these templates (put them in header file):
[ these were in a FAQ, but, I couldn't remember which one[1], so, I post
it.<G>]
[snipped code]

It's not the same code you posted, but it handles bad conversion:

From 39.1 to 39.3:
http://www.parashift.com/c++-faq-lit...al-issues.html
Guess what? I clicked your link while off-line and up-it-poped! That was what
I was looking for, thanks. [d a r n CRS!!]

Now I only have to do a search for what dang partition/folder I put it in!
[..and move it to the proper place - in my library.]

--
Bob R
POVrookie
Oct 11 '06 #10

F.J.K. 写道:
vi******@gmail.com wrote:
I was trying to cast some strings to integers with stringstream, then
this strange problem poped up.
Here is my test code:

Doesn't compile. Please post complete programs, see
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8

stringstream conv;
string from;
int to;

from = "1";
conv << from;
conv >to;

So what do you think happens in the last line. To be like the library,
you have to think like the library :-) You read all characters upto and
including EOF. Thus setting state |= eofbit in conv. Thus making the
stream invalid for all further operations.
Thanks, this explains everything, I didn't notice the state change,
though I did notice that once the internal pointer reach the end of the
buffer, the next read/write operation would fail ;)
>

from = "2";
conv << from;
conv >to;

The << operator returns without doing anything, because your eofbit is
set. The >operator returns without doing anything, because the eofbit
is set.
conv.str() returned "1" after 'from = "2"; conv << from;' was executed.

Well, conv << from; was a NOP for the reasons mentioned. conv.str() is
"1" before you do nothing. It will still return "1" after you do
nothing.
Then I explicitly changed the buffer of conv, like this:

conv.str("1");
conv >to;

conv.str("2");
conv >to;

Still, the first casting worked perfectly, the second one failed, to ==
1.

There is no casting in your code. You probably have a scripting
language background, like perl. The terms we use in C++ for read
operations is something like "the first read". Casting is a different
concept and quite a subject in itself. Btw, if you take care not to
read EOF by adding a whitespace like " " or "\n", everything works
fine.

#include <sstream>
#include <iostream>

int main () {
std::stringstream conv("1\n");
int to;
conv >to;
std::cout << to << "\n";
conv.str("2\n");
conv >to;
std::cout << to << "\n";
}
I'm wondering I've terribly misunderstanding something, sorry if I'm
asking the obvious.

Your doing fine. You are just a little bit careless. And you should use
an IDE with a debugger. If you singlestep your program, the state
member of your stringstream will instantly tell you what's happend.
Oct 11 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Bill Beacom | last post by:
Hi all, I am trying to use stringstream to assemble a text message from a set of user-defined objects that have the insertion operator overloaded. It seems to be putting them into the...
2
by: Woodster | last post by:
I am using std::stringstream to format a string. How can I clear the stringstream variable I am using to "re use" the same variable? Eg: Using std::string std::string buffer; buffer =...
3
by: Mike Chirico | last post by:
Sorry about the newbie question. What's the best way to convert numbers to strings in C++. The following works, but is it better than using the sprintf() "old C" way of converting? #include...
5
by: cherico | last post by:
I'd like to read stings from cin and put them in stringstream. I use a string object as an intermediate "container" to store data from cin and then put them in stringstream. stringstream ss ;...
5
by: William Payne | last post by:
How do you get rid the contents in a std::stringstream? I'm using one in a for loop to format some status messages which I print to the screen. The stringstream member function clear() only clears...
3
by: jdm | last post by:
In the sample code for the SortedList class, I see the use of a string typecasting macro consisting of a single letter "S". i.e.: Sortedlist->Add(S"Keyval one", S"Item one"); Now I have...
24
by: asdf | last post by:
I got a warning from the following statement: fprintf(point_file, "CONTOUR\nCLOSE\n%d\n", curve.size()); warning: format '%d' expects type 'int', but argument 3 has type 'size_t' should I...
2
by: linyanhung | last post by:
In case A(see below), ss.clear() doesn't work and have no error message. cout<<ss.str() shows "xcv". In case B ss.clear() works normally and cout<<ss.str() shows nothing. Can...
2
by: drusakov | last post by:
consider the following piece of code, compiled with g++ 3.4 and stlport 5.1 on Linux 64 bit (problem persists in 32 bit too) std::stringstream ss; int ii = 123; ss << "test1";...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shllpp 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.