Home c++ How to replace the stoi function?

How to replace the stoi function?

Author

Date

Category

The program needs to translate the string into an integer. I tried to use the stoi function for this purpose, but it is not accepted – an error comes out:

'stoi' was not declared in this scope

Specifically, I need to translate a string like this "5678906576" to an integer. I tried to replace it with atoi using c_str beforehand. I write:

string str = "5678906576";
cout & lt; & lt; atoi (str.c_str ()) & lt; & lt; endl;

I get in the console 1383939280 .

Then I try the fromStdString (). toInt () function from Qt Core . I write:

string str = "5678906576";
cout & lt; & lt; QString :: fromStdString (str) .toInt () & lt; & lt; endl;

I get 0.

Gentlemen, please explain why this is so and how I then replace stoi .

I’m using Qt 4.7.4 QtCreator-2.4.1.


Answer 1, authority 100%

To use stoi, you need to include the header file

# include & lt; string & gt;

and use it like this

# include & lt; string & gt;
int main ()
{
  std :: string str1 = "45";
  std :: string str2 = "3.14159";
  int myint1 = std :: stoi (str1);
  int myint2 = std :: stoi (str2);
}

the function and usage are described in std :: stoi, std :: stol , std :: stoll


Answer 2, authority 100%

So

string str = "5678906576";
cout & lt; & lt; atoi (str.c_str ()) & lt; & lt; endl;

you can. But here you have the problem of going beyond the scope of int , here you needed

cout & lt; & lt; atoll (str.c_str ()) & lt; & lt; endl;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions