Adrian
Adrian

Reputation: 502

How to get int from string (string using like a array of char)

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

Upvotes: 1

Views: 164

Answers (4)

Slava
Slava

Reputation: 44288

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

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);

Upvotes: 2

molbdnilo
molbdnilo

Reputation: 66459

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';

Upvotes: 0

The Techel
The Techel

Reputation: 873

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?

Upvotes: 0

Related Questions