Convert String to Integer (str to int) using C++ [Urdu / Hindi]

Convert string to integer in C++

In this video, we are going to solve a C++ programming problem where are given a string and we have to convert it into an integer (str to int). In this video, we will try to handle all the cases that might break our code.

Series playlist ▶︎ https://youtube.com/playlist?list=PLt4rWC_3rBbWnDrIv4IeC4Vm7PN1wvrNg 

Source Code:

#include <iostream>
#include <cstring>
#include <string_view>

int64_t str_to_int64(std::string_view number) {
    int64_t converted_number{};
    bool is_positive{ true };
    size_t valid_pos{};

    // Skipping to the actual number (if found)
    for (auto each : number)
    {
        if (isdigit(each)) break;
        valid_pos++; // 1
    }

    // Checking for negative number
    if (valid_pos > 0 and number[valid_pos-1] == '-') is_positive = false;

    // Actual conversion
    for (size_t i{valid_pos}; i < number.length() and isdigit(number[i]); i++) // 3, 3
    {
        converted_number *= 10;                 // 238
        converted_number += number[i] - 48;     // 8
    }

    return is_positive ? converted_number : -converted_number;
}

int main() {
    std::string str_number{ "      32fw5eoi" };

    auto number {str_to_int64(str_number)};

    std::cout << number << '\n';

}

Watch The Video:

Post a Comment

0 Comments