1

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)
}

2 Answers 2

5

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

6
  • This is unnecessary on my machine. Maybe it's an OS difference? Jan 26, 2018 at 5:13
  • I'm on Windows 7. Jan 26, 2018 at 5:14
  • @CoreyOgburn, it seems this is happening on windows. Jan 26, 2018 at 5:14
  • @KadeWilliams so it should fix your issue. Jan 26, 2018 at 5:15
  • That worked. I searched Google for a while and didn't see anything on that. Jan 26, 2018 at 5:17
2

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.

1
  • It is still doing the same thing. It does not allow a user to enter a name, before and after the change. Once you type 1, it runs through to the end of the program. Jan 26, 2018 at 5:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.