Post

atoi in c++

In C++, atoi stands for ASCII to Integer. It is a standard library function used to convert a C-style string (a const char*) representing a numeric value into an int.

Usage

The function is declared in the header <cstdlib> and its syntax is:

1
int atoi(const char *str);
  • str: A C-style string containing the numeric value to be converted.

Example

Here’s a simple example:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdlib> // for atoi

int main() {
    const char* str = "1234";
    int number = atoi(str);

    std::cout << "The integer is: " << number << std::endl; // Outputs: The integer is: 1234
    return 0;
}

Important Notes

  • No Error Checking: atoi does not handle errors well. If the input string is not a valid number, it returns 0, which can lead to ambiguity if the string itself represents 0.
  • Safer Alternatives: For better error handling and conversion, use std::stoi (C++11 and later) or functions like std::strtol.

Summary

atoi is a simple function for converting a C-style string to an integer but has limited error handling capabilities.

This post is licensed under CC BY 4.0 by the author.

Impressum  | 

Datenschutz  | 

Manage cookie settings  | 

Using the Chirpy theme for Jekyll

© 2024 CodingTarik. Some rights reserved.