example3_conversions_arithmetic.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>

int main() {
    // String to integer conversion
    const char* str_int = "123";
    int num_int = std::atoi(str_int);
    std::cout << "String to int: " << num_int << std::endl;

    // String to double conversion
    const char* str_double = "3.14159";
    double num_double = std::atof(str_double);
    std::cout << "String to double: " << num_double << std::endl;

    // Integer to string conversion (C++ style)
    std::string int_str = std::to_string(num_int);
    std::cout << "Int to string: " << int_str << std::endl;

    // Absolute value
    int negative = -42;
    std::cout << "Absolute value of " << negative << ": " << std::abs(negative) << std::endl;

    // Division and modulus
    int dividend = 17, divisor = 5;
    std::div_t result = std::div(dividend, divisor);
    std::cout << dividend << " divided by " << divisor << " is " 
              << result.quot << " with remainder " << result.rem << std::endl;

    return EXIT_SUCCESS;
}
Back to cstdlib