0

I am very new at coding so bare with me. I was using fgets for an assignment which included asking questions to the viewer. Every time I had a line with fgets, it would jump directly to the next question without letting the viewer answer the first question asked. (I'm using Repl.it btw)

Code section that's not working:

printf("What's your eye colour?");
scanf("%s", colour);

printf("What country do you want to visit?");
fgets(country, 20, stdin);

printf("How many pets do you have?");
scanf("%d", &pets);

Result:

What's your eye colour? Blue
What country do you want to visit?How many pets do you have?

I have to use fgets, not scanf because the answer needs to have a blank space. Thank you to anyone that can help out!

Artemis
  • 3
  • 1
  • 1
    If it were me, I'd probably use `fgets()` for all the input. But note that `fgets()` retains the `'\n'` at the end of the string, so you might want to [remove that](https://stackoverflow.com/q/2693776/100770). – Fred Larson Nov 17 '20 at 18:17
  • What do you mean by retains \n? how do I remove it? Thanks! – Artemis Nov 17 '20 at 18:27
  • And FWIW, I think the [top voted answer](https://stackoverflow.com/a/28462221/10077) is better than the accepted answer. – Fred Larson Nov 17 '20 at 18:28
  • I mean, if the user types "Italy" and hits the enter key, the resulting string in `country` will be `"Italy\n"`. That's likely to screw up any output you attempt with this. To remove it, see the link in my previous comment. – Fred Larson Nov 17 '20 at 18:29
  • The issue isn't after the user types a country, It asks both those questions at once, without allowing the viewer to answer the first one. – Artemis Nov 17 '20 at 18:36
  • 1
    Not if you use `fgets()` instead of `scanf()` for the first question. See the duplicate. The `scanf()` is leaving the `'\n'` in the stream, so that's all you get for the answer to your second question. – Fred Larson Nov 17 '20 at 19:04
  • Oh, that worked. thank you! – Artemis Nov 17 '20 at 19:41

0 Answers0