Having problems with the atoi function

I am trying to convert the contents of string num to an integer variable sum but for some reason my code will not compile. Can some one please tell me what I am doing wrong? Thanks so much!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
    string num = "435";
    int sum = 0;

    sum = atoi(num);

    cout << sum  << endl;

    return 0;
}

atoi() expects a plain c-string, that is a null-terminated array of characters.
To convert a c++ std::string use the c_str() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
    string num = "435";
    char   num2[] = "765";
    
    int sum = 0;

    sum = atoi(num.c_str());
    cout << sum  << endl;

    sum = atoi(num2);
    cout << sum  << endl;

    return 0;
}
Last edited on
Thanks
Topic archived. No new replies allowed.