Converting String to int

Converting String to int

ยท

2 min read

The Approach

  1. Reading Input

    • The code uses bufio.NewReader(os.Stdin) to create a new reader that reads from the standard input stream (terminal).

    • reader.ReadString('\n') reads input from the user until a newline character (\n) is encountered.

  2. Parsing Input

    • The input read from the user is initially a string (e.g., "42\n").

    • To convert the string to an integer, the code uses strconv.ParseInt(strings.TrimSpace(input), 10, 64).

    • strings.TrimSpace(input) removes any leading or trailing whitespace (including the newline character) from the input string.

    • strconv.ParseInt(trimmedInput, 10, 64) then parses the trimmed input string as a base-10 integer, returning a 64-bit signed integer value.

  3. Performing the Operation

    • After parsing the input string to an integer, the code adds 1 to the integer value using the expression number + 1.
  4. Printing the Result

    • Finally, the code prints the new number (the original input plus 1) to the console using fmt.Println("new number is: ", number).

Key Considerations

  • Handling Newline Characters: The code uses strings.TrimSpace(input) to remove the newline character (\n) from the input string before parsing it as an integer. This is necessary because the strconv.ParseInt function expects a clean numeric string without any extra characters.

  • Error Handling: In the provided code, error handling is omitted by using the blank identifier (_) to discard the error value returned by strconv.ParseInt. In production code, it's generally recommended to handle errors appropriately, such as displaying an error message or taking appropriate action.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)

    fmt.Println("Enter a number: ")

    input, _ := reader.ReadString('\n') //remember that the string will include \n (a line break) in it

    fmt.Println("input string is : ", input)

    // add 1 to the input number which is in string format

    /*
        number, err := strconv.ParseInt(input, 10, 32)

        // the input contains a '\n' at the end hence cant be parsed into int
        // hence above parsing will give error
        if err != nil {
            fmt.Println("error occured", err)
        } else {
            number = number + 1
            fmt.Println(number)
        }
    */

    number, _ := strconv.ParseInt(strings.TrimSpace(input), 10, 64)
    // if error handling is not needed just put an _ there

    number = number + 1
    fmt.Println("new number is: ", number)

}
ย