Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ weird problem converting a char to int

Tags:

c++

atoi

I'm a total newbie to C++ and I was trying to do one of the problems from Project Euler when I had a very weird problem. I reduced the error to the following.

Consider the following simple code:

#include <iostream>

using namespace std;

int main() {
    int numdigits;
    cout << "digits: ";
    cin >> numdigits;

    char tmpchar;
    cin >> tmpchar;
    cout << atoi(&tmpchar) << endl;
    return 0;
}

Basically if the first input (numdigits) is below 48 everything works fine but if the input is 48 or greater if have a very weird behaviour:

air:programming santi$ ./lol
digits: 30
3
3                            <--- OK
air:programming santi$ ./lol
digits: 48
3
30                           <--- Not OK
air:programming santi$ ./lol
digits: 49
3
31                           <--- Not OK
air:programming santi$ ./lol
digits: 50
3
32                           <--- Not OK

What is going on? I got mad trying to find the error in the algorithm until I found out that the error was in that part of the code where I didn't bother to look at first.

Thanks in advance!

like image 247
curial Avatar asked Dec 02 '22 01:12

curial


1 Answers

The problem is here:

char tmpchar;
cin >> tmpchar;
cout << atoi(&tmpchar) << endl;

atoi expects a NUL-terminated string, which isn't what you're giving it (there's no NUL character except that you may be sometimes getting one by chance).

A possible (ugly) fix is:

char tmpchar[2] = {0};
cin >> tmpchar[0];
cout << atoi(tmpchar) << endl;

If you're dealing with multiple-character strings, then using std::string would be the way to go:

std::string str;
cin >> str;
cout << atoi(str.c_str()) << endl;
like image 66
NPE Avatar answered Dec 18 '22 07:12

NPE