1

this little program describes my problem which I have in bigger project:

int main()
{
    string str1="11111111";
    string str2="22222222";

    char a=str1[2];
    char *a1=&a;
    int var1= atoi(a1);

    char b=str2[2];
    char *b1=&b;
    int var2= atoi(b1);

    cout<<var1<<endl;
    cout<<var2;


    return 0;
}

Why I'm getting

1
21

istead of

1
2

?

Is there any way to fix this? - thanks for the help I trying to figureout for two hours

Adrian
  • 482
  • 5
  • 20

4 Answers4

2

You get both results by mistake (even though your first result happens to match your expectation).

The problem is that both a1 and b1 point to a single character, while atoi expects a null-terminated string.

You can fix this problem by constructing character arrays instead of copying individual characters:

char a1[2] = { str1[2] };   // C++ compiler supplies null terminator, you supply the size
int var1= atoi(a1);
char b1[] = { str2[2], 0 }; // You supply null terminator, C++ compiler computes the size
int var1= atoi(b1);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Use std::stoi() and std::string::substr() especially if you have std::string already:

std::string str1="11111111";
std::string str2="22222222";

int var1= std::stoi( str1.substr( 2, 1 ) ); // third symbol, 1 symbol long

int var2= std::stoi( str2.substr( 2, 1 ) );

live example

Slava
  • 43,454
  • 1
  • 47
  • 90
0

atoi expects a pointer to a null-terminated string of char. You pass a pointer to a char. What happens is undefined. You better use std::stoi instead of atoi since atoi has some fallacies: What is the difference between std::atoi() and std::stoi?

Community
  • 1
  • 1
The Techel
  • 918
  • 8
  • 13
0

atoi wants a pointer to the first element of a zero-terminated sequence of characters.
You're passing it a pointer to a single character, leaving undefined behaviour in your wake.

To get the integer value of one of the digits, take its distance from '0':

int var = str1[2] - '0';
molbdnilo
  • 64,751
  • 3
  • 43
  • 82