C atoll() Function | Convert String to Long Long Integer

Introduction

The atoll() function in C is a standard library function that converts a string to a long long integer. It is part of the C standard library (stdlib.h). It is commonly used to convert string representations of long long integers into their corresponding long long integer values.

atoll() Function Syntax

The syntax for the atoll() function is as follows:

long long int atoll(const char *str);

Parameters:

  • str: A C string that contains the representation of a long long integer.

Returns:

  • The function returns the converted long long integer value. If no valid conversion could be performed, it returns 0.

Examples

Converting a Simple String to Long Long Integer

To demonstrate how to use atoll() to convert a string to a long long integer, we will write a simple program.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *str = "123456789012345";
    long long int num;

    // Convert string to long long integer
    num = atoll(str);

    // Print the converted value
    printf("The converted value is: %lld\n", num);

    return 0;
}

Output:

The converted value is: 123456789012345

Handling Invalid Input

This example shows how atoll() behaves with invalid input.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *str = "abc123";
    long long int num;

    // Convert string to long long integer
    num = atoll(str);

    // Print the converted value
    printf("The converted value is: %lld\n", num);

    return 0;
}

Output:

The converted value is: 0

Real-World Use Case

Converting User Input to Long Long Integer

In real-world applications, the atoll() function can be used to convert user input, provided as a string, into a long long integer for further numerical processing.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    char input[100];
    long long int value;

    // Prompt the user for input
    printf("Enter a long long integer: ");
    fgets(input, sizeof(input), stdin);

    // Convert input to long long integer
    value = atoll(input);

    // Print the converted value
    printf("You entered: %lld\n", value);

    return 0;
}

Output (example user input "1234567890123456789"):

Enter a long long integer: 1234567890123456789
You entered: 1234567890123456789

Conclusion

The atoll() function is used to convert strings to long integer values in C. By understanding and using this function, you can effectively manage and process numerical data stored as strings in your C programs, especially when dealing with very large numbers. Always handle invalid input scenarios to ensure robust applications.

Comments