Error displayed

Hello, the code below displays an error, but I can't pinpoint why. Is this due to my use of constants?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()

{
string q;
int i;

cin >> q;

i = atoi(q);

cout << i;

return 0;
}
Last edited on
In function 'int main()':
15:11: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'

Try say
i = atoi(q.c_str());

But there are better ways to convert strings to ints in C++.
Change atoi to stoi and you'll be fine.

There are null-terminated c-strings inherited from C and the string class which came in with c++. atoi() expects the former and stoi() the latter.
Last edited on
Topic archived. No new replies allowed.