473,848 Members | 1,559 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using std::stringstre am to convert a char to int

I wrote the following function as a curiosity:

template<typena me SourceType,
typename DestinationType >
DestinationType NumericCast(con st SourceType& value) {
std::wstringstr eam strbuf;
strbuf << value << std::endl ;
strbuf.flush();
DestinationType convalue;
strbuf >> convalue;
return convalue;
}

This works fine for all numeric types such as int to long, long to
float etc.

However, I tried the following:

NumericCast<cha r, int>('c');

This failed to return the correct value. When I stepped through the
function, the value of "convalue" remained the same throughout. But
this happened only when SourceType was char. A

I tried stepping into the operator code, but my debugger just stepped
over so I am not sure what's going on inside.

Anyone have any ideas on anything I am doing that is obviously wrong,
but which I am missing?

thanks,

-vijai.

Nov 6 '05 #1
4 12183
"Vijai Kalyan" <vi**********@g mail.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .

Re: Using std::strinstrea m to convert a char to int

That doesn't make any sense. Type 'char' objects
already are integers. stringstreams are for working
with strings. Neither a 'char' nor an 'int' are strings.
More below.
I wrote the following function as a curiosity:

template<typena me SourceType,
typename DestinationType >
DestinationType NumericCast(con st SourceType& value) {
std::wstringstr eam strbuf;
strbuf << value << std::endl ;
strbuf.flush();
DestinationType convalue;
strbuf >> convalue;
return convalue;
}

This works fine for all numeric types such as int to long, long to
float etc.

However, I tried the following:

NumericCast<cha r, int>('c');

This failed to return the correct value.
That's because you probably don't understand what
'correct value' means with a stringstream as you're
using it.
When I stepped through the
function, the value of "convalue" remained the same throughout. But
this happened only when SourceType was char. A

I tried stepping into the operator code, but my debugger just stepped
over so I am not sure what's going on inside.

Anyone have any ideas on anything I am doing that is obviously wrong,
but which I am missing?


If you want to convert a type 'char' to a type 'int', simply write:

char c = 42;
int i = 0;

i = c;

What you're probably not realizing is that what a stringstream
does with numeric objects is translate the *text* representation
of a value (e.g "123") to its binary representation ( int(123) ),
or the inverse conversion ( int(123) to "123"). Sinc both 'char'
and 'int' are already numeric types, there's no text involved.

There's a reason that type 'stringstream' has the word 'string'
as part of its name. :-)

-Mike
Nov 6 '05 #2
Hi Mike. Thanks for your reply. That is interesting to know.

I read online a long time about how we can convert numeric values to
their string representations by using a stringstream. Or was that a
stringbuf? What's the difference?

Anyway, I was playing around with the above simple as an extension of
that idea.

But, I am still cuious about why it still works for the other numeric
types but not for a char.

regards,

-vijai.

Nov 6 '05 #3

"Vijai Kalyan" <vi**********@g mail.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Hi Mike. Thanks for your reply. That is interesting to know.

I read online a long time about how we can convert numeric values to
their string representations by using a stringstream.
That would be a 'ostringstream' . 'istringstream' is
for the inverse, and 'stringstream' can do both.
Or was that a
stringbuf? What's the difference?
'stringbuf' is a supporting type used by the 'stringstream'
types in their implementation.

Anyway, I was playing around with the above simple as an extension of
that idea.

But, I am still cuious about why it still works for the other numeric
types but not for a char.


It does work. You just need to remember that type
'char' is an integer type, and that it's not a string.

#include <iostream>
#include <sstream>
#include <string>

int main()
{
char c = 'X';
std::ostringstr eam oss;
oss << c;
std::string s(oss.str());
std::cout << s << '\n'; /* prints X */
std::istringstr eam iss(std::string (1, 'A'));
iss >> c;
std::cout << c << '\n'; /* prints A */
return 0;
}

-Mike
Nov 6 '05 #4
Ian
Vijai Kalyan wrote:
Hi Mike. Thanks for your reply. That is interesting to know.

I read online a long time about how we can convert numeric values to
their string representations by using a stringstream. Or was that a
stringbuf? What's the difference?

Anyway, I was playing around with the above simple as an extension of
that idea.

But, I am still cuious about why it still works for the other numeric
types but not for a char.

Because the string representation of any other numeric type is a number,
while the string representation of 'c' is 'c'.

streaming 'c' into and int isn't a good idea.

Ian
Nov 6 '05 #5

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

Similar topics

6
36553
by: Giampiero Gabbiani | last post by:
Is it possible to reset a std::stringstream in order to reuse it once more? I tried with flush() method without any success... Thanks in advance Giampiero
5
12084
by: Mr Fish | last post by:
Is it possible for me to record floats in a std::stringstream with 100% accuracy? If so how? Here's a little prog that demonstrates how the default ss loses accuracy //----------------------------------------------------------------------------- #include <sstream> #include <iostream> using namespace std;
5
4223
by: Marcin Kalicinski | last post by:
Is there a vectorstream class that implements the functionality similar to std::stringstream but with std::vector, not std::string? cheers, Marcin
5
3647
by: ma740988 | last post by:
Consider: #include <iostream> #include <sstream> #include <string> int main ( ) { { double pi = 3.141592653589793238; std::stringstream a;
2
4863
by: avidamani | last post by:
Hi, I have a c++ application compiled using Compaq C++ V6.5-014 for Compaq Tru64 UNIX V5.1A (Rev. 1885) Compiler Driver V6.5-014 (cxx) cxx Driver The problem is that the application is having unaligned access error and is core dumping whenever I use stringstream to convert integer or long to string.
1
2904
by: magix | last post by:
I got this reply in my previous post a month ago: May I know, how can I automatically create the folder if it doesn't exist ? In previous reply, it said: ------------------------- std::stringstream stream; stream << "C:\\Output\\Output.txt" << std::flush; std::ofstream SaveFile(stream.str().c_str()); The "C:\Output" must already exist?
7
3613
by: Ziyan | last post by:
I am writing a C/C++ program that runs in background (Linux). Therefore, normally no output would be written into standard output. However, sometimes I want to have debug message collected and sent tho network to a client so that errors and debug messages can be displayed simultaneously anywhere. I tried to use a std::stringstream to do the job. I created the stringstream in main() and pass it as pointer into a few threads. Those threads...
7
13647
by: Grey Alien | last post by:
Does *ANYONE* in here know how I may parse the various date/time 'elements' from a string?. The input string has the ff format: 'YYYY-MM-DD HH:MM:SS AM'
7
3320
by: TBass | last post by:
Hi. I wrote a "tag" class to store values. The user gets to store most any type he would need. Instead of getting too complicatated, I decided I would store the value as a stringstream, then overload the SetValue method. .... protected:
3
5910
by: Rune Allnor | last post by:
Hi all. I am trying to use std::stringstream to validate input from a file. The strategy is to read a line from the file into a std::string and feed this std::string to an object which breaks it up into individual elements. The elements can be strings, integers or floating point numbers. In the object where I break the line into elements I use a std::stringstream object to do the actual check:
0
10997
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10661
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...
1
10718
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7067
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5731
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
5917
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4542
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
4134
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3172
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.