Kade Williams
Kade Williams

Reputation: 1181

Why is second scanf being skipped over?

I decided to take a look at Go and I am currently stuck on something. In this program, I am asking the user to choose option 1 or 2. If option 1 is chosen, I want the ReadAppList function to ask the user for a last name.

It seems as if the second scanf is being skipped over and not allowing the user to enter a last name. Is it only reading the first user input?

package main

import (
    "fmt"
)


// Main function that runs on startup
func main() {

    fmt.Println("\n1. Search Last Name ")
    fmt.Println("\n2. Exit ")
    fmt.Println("\nPick an option: ")
    var userAnswer int
    fmt.Scanf("%d", &userAnswer)

    if userAnswer == 1 {

        ReadAppsList()

    } else if userAnswer == 2 {

        fmt.Println("\nGoodbye.")

    } else {

        fmt.Println("\nThat is not a valid choice.")

    }
}

func ReadAppsList() {

    fmt.Println("\nType your LastName of the person you want to look up: ")
    var lastName string
    fmt.Scanf("%s", &lastName)
    fmt.Sprintf("You typed %s", lastName)
}

Upvotes: 1

Views: 872

Answers (2)

Ashkan Nourzadeh
Ashkan Nourzadeh

Reputation: 1942

That's because extra newline not being consumed by first scanf.
Change your scanf to this fmt.Scanf("%d\n", &userAnswer).

Upvotes: 5

Corey Ogburn
Corey Ogburn

Reputation: 24759

In your ReadAppsList you have:

fmt.Sprintf("You typed %s", lastName)

The problem is that Sprintf returns a string without writing to the screen. Change that to Printf and it'll print the lastname.

The Scanf for the last name is happening as you'd expect.

Upvotes: 2

Related Questions