Home »
C++ programming language
atoi() Function with Example in C++
C++ atoi() function: Here, we are going to learn about the atoi() function with example of cstdlib header in C++ programming language.
Submitted by IncludeHelp, on May 26, 2020
C++ atoi() function
atoi() function is a library function of cstdlib header. It is used to convert the given string value to the integer value. It accepts a string containing an integer (integral) number and returns its integer value.
Syntax
Syntax of atoi() function:
C++11:
int atoi (const char * str);
Parameter(s)
- str – represents a string containing an integer (integral) number.
Return value
The return type of this function is int, it returns the integer converted value.
Sample Input and Output
Input:
str = "123";
Function call:
atoi(str);
Output:
123
Example
C++ code to demonstrate the example of atoi() function:
// C++ code to demonstrate the example of
// atoi() function
#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
// main() section
int main()
{
char str[50];
strcpy(str, "123");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
strcpy(str, "-123");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
strcpy(str, "0");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
strcpy(str, "1234567");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
strcpy(str, "12345678");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
strcpy(str, "-12345678");
cout << "atoi(\"" << str << "\"): " << atoi(str) << endl;
return 0;
}
Output
atoi("123"): 123
atoi("-123"): -123
atoi("0"): 0
atoi("1234567"): 1234567
atoi("12345678"): 12345678
atoi("-12345678"): -12345678
Reference: C++ atoi() function