Strange problem when converting char to int

Started by
3 comments, last by mikeman 16 years, 11 months ago

#include <string>
#include <iostream>

using namespace std;

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

output: 43
Everyone hates #1.That's why a lot of idiots complain about WoW, the current president, and why they all loved google so much when it was new.Forget the fact that WoW is the greatest game ever created, our president rocks and the brainless buffons of America care more about how articulate you are than your decision making skills, and that google supports adware, spyware, and communism.
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;}
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.
Everyone hates #1.That's why a lot of idiots complain about WoW, the current president, and why they all loved google so much when it was new.Forget the fact that WoW is the greatest game ever created, our president rocks and the brainless buffons of America care more about how articulate you are than your decision making skills, and that google supports adware, spyware, and communism.
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]
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.

This topic is closed to new replies.

Advertisement