Sign in to follow this  

C++ char to int.

This topic is 4276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If you only need single digits converted, you can use something like this:

int char2int( char c ) {
return c - '0';
}


No error checking, and it's not very sophisticated, but it works. For anything more complex than that (say, converting a string to an int), use atoi (C-style) or a stringstream (C++ style). But the point is, chars are themselves integers, and are in order starting with '0'. Subtract '0', and you get its integer value.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by damastaplaya
i would guess something like this:

int a == 2;
char b == 'two';
if (a && b == 2 || 'two')
{
\\process goes here
}

but ima newbie v_v


What, that doesn't make any sense. You used the comparison operator for assignment(should be = instead of ==) and you assigned(or attempted to) three characters(which can't be done) to just a char. Plus that if statement doesn't work at all.

Share this post


Link to post
Share on other sites
Quote:
Original post by damastaplaya
i would guess something like this:

int a == 2;
char b == 'two';
if (a && b == 2 || 'two')
{
\\process goes here
}

but ima newbie v_v


Okay.

I would suggest that if you are unsure of how you can help, you can try make a little test program to try it out. For example, the code you posted will not compile.

And there are more elegant solutions than comparing with all possible values in this case.

Share this post


Link to post
Share on other sites
Quote:
Original post by rip-off
Quote:
Original post by damastaplaya
i would guess something like this:

int a == 2;
char b == 'two';
if (a && b == 2 || 'two')
{
\\process goes here
}

but ima newbie v_v


Okay.

I would suggest that if you are unsure of how you can help, you can try make a little test program to try it out. For example, the code you posted will not compile.

And there are more elegant solutions than comparing with all possible values in this case.


Well other than the compare for assignment, it would compile... (Unless you are talking about specifically that [grin].)

Now the problem is that a 'two' character would be really quiet and compile, turning into a big bug, so watch out for that damastaplaya :).

Unless... You have warnings reported 100% of the time like me :).

@OP: Google for "ascii table" and click on any of the first like .....3 matches.

I found these tables really fun and useful, because that's how characters are set up. After you know where a '0' is and other things things turn really logical and simple [wink].

Share this post


Link to post
Share on other sites
Quote:
Original post by damastaplaya
int a == 2;
char b == 'two';
if (a && b == 2 || 'two')
{
\\process goes here
}


Erm.. I don't think there could be any more wrong with this code. There are only two lines that will compile, and those are only brackets.

== is the comparison operators, = is the assignment operator. Don't mix them up. A char variable holds a single character, not a character string. A character string is quoted with "double quotes", a single character is quoted with 'single quotes'. They are not interchangable. Also, he wanted to convert '2' to 2, not "two" to 2. "if( a && b == 2 || 'two' )" doesn't do what you want it to. If a evaluates to true (2 does, so yes) and b == 2 ('two' probably means 't', so no, false) or if 'two' evaluates to true ('t' does, so true), then do something. I just don't know what you're intending to say here. Comments use //forward slashes, not \\backslashes.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
what if you needed to do this with double digits. say u had string x=12
and u wanted to conver that to int 12.

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
what if you needed to do this with double digits. say u had string x=12
and u wanted to conver that to int 12.


#include <sstream>
#include <string>

int stringToInt( const std::string &str )
{
std::stringstream stream;
stream << str;
int value;
stream >> value;
return value;
}





EDIT: Whoops got the "<<" ">>" the wrong way around... I had to put source tags in, and when i edited, i found all my pretty "<<" replaced by html. I musn't have looked close enough at the lt and gt symbols [embarrass]

[Edited by - rip-off on April 3, 2006 11:43:15 AM]

Share this post


Link to post
Share on other sites
#include <string>
#include <sstream>

int main() {
std::stringstream stream;
std::string str( "12" );
stream.str( str );
int num;
stream >> num;
}
or boost::lexical_cast.


jfl.

[edit] Beaten.

Share this post


Link to post
Share on other sites
If you are going to use std::stringstream, there's a briefer form you can use:
int str2int( std::string str )
{
int result = 0;
std::stringstream( str ) >> result;

return result;
}

Share this post


Link to post
Share on other sites
If what you're trying to do is convert an integer to a string or visa-versa, use boost, please. It has to be one of the most useful swiss-army knives you'll find for coding:


#include <boost/lexical_cast.hpp>
#include <string>

int main()
{
std::string str = "156";
int number;

number = boost::lexical_cast<int> (str);

std::string str2;
int number2 = 5182;
str2 = boost::lexical_cast<std::string> (number2);
}



Use boost! It's got lots of other nice tools. I would say that boost and STL are the two most fundamental tools you should learn to use.

Share this post


Link to post
Share on other sites
Quote:
Original post by Beer Hunter
Quote:
Original post by jonahrowley
Or using the (simpler) C function atoi:
But note that atoi("lol") returns zero. If that's acceptable, go for it.


I don't think atoi() is in the C++ standard, so I don't think there is an official way an implementation should handle this case. I don't think using atoi() is a good idea, use string streams.

Share this post


Link to post
Share on other sites
i have a quick question. what's the difference between these two methods:

std::stringstream stream;
stream >> str;
int value;
stream << value;
return value;


and

std::stringstream stream;
std::string str( "12" );
stream.str( str );
int num;
stream >> num;

or

int result = 0;
std::stringstream( str ) >> result;
return result;

Share this post


Link to post
Share on other sites
They should all give you the same result(s).

For the first example, I think you mean:

std::string str("123");
std::stringstream stream;
stream << str;
int value;
stream >> value;
return value;


Share this post


Link to post
Share on other sites

std::stringstream stream;
stream >> str;
int value;
stream << value;
return value;


This returns garbage.



std::stringstream stream;
std::string str( "12" );
stream.str( str );
int num;
stream >> num;


num will contain the integer 12.



int result = 0;
std::stringstream( str ) >> result;
return result;


This is the most readable and cleanest method of converting std::string str to int result.

Share this post


Link to post
Share on other sites
[quote]i have a quick question. what's the difference between these two methods:

std::stringstream stream;
stream >> str;
int value;
stream << value;
return value;


and
std::stringstream stream;
std::string str( "12" );
stream.str( str );
int num;
stream >> num;

or

int result = 0;
std::stringstream( str ) >> result;
return result;

[/quote
Well, it looks like the first one doesn't do anything that resembles something useful. What it does is take the info in the stream(in this case nothing, it wasn't initialized), and then outputs that nothing into str. Next, stream << value will try and putting the data in value inside the stream. Value wasn't initialized, so the number put in stream will likely be random. then it returns value, which wasn't initialized.

The 2nd one constructs a string with the value "12". stream.str(str) assigns str to stream(basically). stream >> num outputs stream into num. This is the form that will enable you to convert a string to an integer.

The 3rd one construct a temporary unnammed stringstream object constructed with the data in str, and then it takes this temporary stream and outputs it's data into result, before finally returning result.

Note: stringstreams also let you convert a number into a string. Can you figure out how?

Share this post


Link to post
Share on other sites
well, i was being lazy when i copied, but the first method comes from an earlier example in this thread. in that case, the string would be initialized. but i should've realized it was a simple "<<" flip mistake. it's just that it was the first string stream example and i assumed it was correct somehow.

Share this post


Link to post
Share on other sites
Quote:
Original post by C J W
I don't think atoi() is in the C++ standard
atoi is standard, but it seems that it doesn't define what happens in the case of error. Still, it can have its uses.

Share this post


Link to post
Share on other sites

This topic is 4276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this