473,657 Members | 2,490 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 misunderstandin g something, sorry if I'm
asking the obvious.

Oct 10 '06 #1
10 2613
<vi******@gmail .comwrote in message
news:11******** *************@c 28g2000cwb.goog legroups.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 misunderstandin g 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::stringstre am 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 misunderstandin g 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************ **********@m7g2 000cwm.googlegr oups.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::stringstre am 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<sstrea m>
#include <iomanip // for 'setprecision() '
template<typena me TT FromString( std::string const &s){
std::istringstr eam is( s ); T t; is >t; return t;
} // FromString(stri ng&)
template<typena me Tstd::string ToString( T const &t, size_t prec = 6){
// std::ostringstr eam s; s << t; return s.str(); // original
std::ostringstr eam s;
s.setf(std::ios _base::fixed);
s <<std::setpreci sion( prec )<< t;
return s.str();
} // ToString(T&,siz e_t)
// ------------------------------------------------------

void TestPrint(){
using std::cout;
double Dnum(12345.6789 );
std::string txt = ToString( Dnum );
double Dnum2 = FromString<doub le>( txt );
cout<<" ------- "<<std::end l;
cout<<" Dnum="<<Dnum<<s td::endl;
cout<<" txt="<<txt<<std ::endl;
cout<<" Dnum2="<<Dnum2< <std::endl;
cout<<" ------- "<<std::end l;
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::end l;
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

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

Similar topics

2
5851
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 stringstream fine....however, I need to assemble it in "parts" (eg a prefix, a header, a body, a trailer and a checksum), and would like to reuse the stringstream to format that various parts....but I ahve not found a successful way to "empty" the...
2
7491
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 = "value1" + " : " + "value2";
3
14798
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 <iostream> #include <string> #include <sstream> #include <list>
5
10874
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 ; string str ; cin >> str ; ss << str ;
5
817
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 flags (bits) in the stream, right? I solved it by declaring the stringstream inside the loop body even though I have need of another stringstream just after the loop. So for each iteration the constructor of the stringstream will be executed. Is...
3
1637
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 deduced that the "S" can be replaced with (String __gc *) and the code will compile and run just fine. But what I can't find is what exactly Microsoft calls these macros (I have also seen "L" used the same way) and where they are all documented. I...
24
2299
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 change the coding to fprintf(point_file, "CONTOUR\nCLOSE\n%u\n", curve.size());
2
1410
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 anyone tell me why ? Thanks. Case A:
2
2209
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"; std::cout<<ss.str()<<std::endl; ss << ii << "test2"; std::cout << ss.str()<<std::endl;
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8603
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.