How to convert String to Int in C++

Asked

Viewed 1,327 times

-1

I’m not able to convert this simple program. how do you convert?

#include <string.h>
#include <stdlib.h>

using namespace std;

int main () {
    int i;
    string a;

    i = atol (a);
}

.

Error message:

Teste 1.cpp:12:16: error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'
     i = atol (a);
                ^
  • atoll receives a const char* as parameter. If you want to convert an Std::string to long int, use stol().

  • Part this, you need to initialize this string with some value.

1 answer

2


Several errors in this code. Starting with include

#include <string.h>
#include <stdlib.h>

string It doesn’t have the extension .h. This is actually a bit confusing, in C++ the library headers do not have extension, but libraries in C do. When you see a library with .h, She’s probably a C library, if she doesn’t have .h, is from C++. As string is a C++ library, remember, it has no extension.

i = atol(a);

Shouldn’t be atoi? ASCII to integer? Still this function will not work, atoi is a function of C. Remember that string is a C++ library? There are no C functions they receive string, functions of C receive *char, then you need to first convert this string for *char with the method a.c_str(). Or else use stoi, string to integer.

Now just initialize your string, after all, if it doesn’t have a value, which you will convert to integer?

#include <string>

using namespace std;

int main () {
    int i;
    string a = "15";

    i = stoi(a);
}

I see in the Ideone.

  • A lot of work goes into the explanation! I’m learning c and c++ together, so I get things confused. But really do it! I have just one question as you commented, no library has the . h? all I can only put the name of the library without the . h? PS: this code I did as an example of what I would do in the real program, in case the string a has value.

  • @Gui_reis, in the case of C, all library headers have .h. In C++, native libraries do not have the extension .h, but C++ also uses C libraries, so you need to know beforehand what kind of library you’re using to know whether or not it has this extension.

  • I get it, it makes sense! Mt obr by explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.