atoi string to int

Explanation of atoi function in C

The atoi function in C is used to convert a string to an integer. It takes a null-terminated string as input and returns the corresponding integer value. Here is an explanation of each step involved in the toInt function, which is a custom implementation of atoi:

  1. Function Signature: The toInt function takes two parameters: a character pointer input representing the string to be converted, and an integer max_value representing the maximum allowed value for the converted integer.

  2. Input Validation: The function first checks whether the input string contains only digits. It iterates through each character of the string using a while loop and checks if each character is a digit using the isdigit function. If any non-digit character is encountered, the function immediately returns -1, indicating that the input was not a positive integer.

c unsigned i = 0; while (i < strlen(input)) { if (!isdigit(input[i])) return -1; i++; }

  1. Conversion: If the input string contains only digits, the function uses the standard atoi function to convert the string to an integer. The converted integer is then checked against the max_value parameter. If the converted integer exceeds the max_value, the function returns -2, indicating that the limit has been exceeded. Otherwise, the function returns the converted positive integer.

c return (atoi(input) > max_value) ? -2 : atoi(input);

That's the explanation of the toInt function, which is a custom implementation of atoi in C. It validates the input string to ensure that it contains only digits and checks if the converted integer exceeds a specified maximum value.

[1]