Jump to content
  • Advertisement
Sign in to follow this  
sharpnova

Strange problem when converting char to int

This topic is 4236 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

#include <string>
#include <iostream>

using namespace std;

int main()
{
        char c1 = '3';
        char c2 = '4';
        cout << atoi(&c2);
        return 0;
}

output: 43

Share this post


Link to post
Share on other sites
Advertisement
I suggest using a stringstream for conversion


#include <sstream>
#include <iostream>
using namespace std;

int main()
{
int i1, i2;
stringstream ss;

// Feed stream with two char items separated by space
ss << '3' << ' ' << '4';

cout << "The stream: " << ss.str() << endl;

if(!(ss >> i1 >> i2)) // extract and convert two items from stream
cerr << "Unable to convert..." << endl;

cout << "The ints: " << i1 << ' ' << i2 << endl;
}



Share this post


Link to post
Share on other sites
But why is the way i'm doing it giving such a weird result?

if i just do it for one char, it works fine

but when i do it for two chars like in the above example, it gives this weirdness..

i'm simply trying to make a menu where the user enters a single digit to specify his/her option and then it converts it to an int. i've never heard of that task requiring anything special. in fact i've never had this issue before.

Share this post


Link to post
Share on other sites
This might clearify:

char c1 = '3';
char c2 = '4';
// The numbers (0-9) starts at index 48 in the ascii table...
cout << (int)c1-48 << ' ' << (int)c2-48 << endl;


The expression &c2 is not good enough.
atoi expect a char array, not the memory address of a single char.

[Edited by - pulpfist on May 11, 2007 10:12:03 PM]

Share this post


Link to post
Share on other sites
What you're doing is wrong. atoi expects a char*, but it supposes it points to a null-terminated string, not a single character. So it keeps reading past the address &c2 until it founds a 0. The result you get is entirely coincidental, it could be any other garbage value or even result in crashing the program. Your best bet is to use std::stringstream pulpfist suggested or boost::lexical_cast. If you don't use boost, I suggest you download it because it's really useful.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!