C++ -------- atoi() function and stoi() function

Foreword:

In C++, there are several functions that deal with string conversion numbers that are very useful, you can learn about it.

atoi() and stoi() functions
  1. Both are C++ character processing functions, which convert digital strings to int output
  2. The header files are #include<cstring>

What is the difference between them?

  1. The parameter of atoi() is const char *, so for the string str, we must call the c_str() method to convert this string into const char *;

  2. The parameter of stoi() is const string *, which can be used directly;

  3. stoi() will do range checking, the default range is in the range of int, if it exceeds the range, it will run a runtime error;

Among them, the stoi() function also has an overloaded version, as follows:

stoi (string, starting position, base n), convert a string in base n to decimal
Example:
stoi(str, 0, 8); //Increase the string str from position 0 to the end by 8 Conversion to decimal

	string s1 = "2147772", s2 = "-214748";
 
	string s3 = "214748666666663", s4 = "-21474836488";
 
	cout << stoi(s1) << endl;
 
	cout << stoi(s2) << endl;
 
	cout << atoi(s3.c_str()) << endl;
 
	cout << atoi(s4.c_str()) << endl;

	cout << stoi(s1,0,8) << endl;

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115177770