0

I can't seem to get either function to do anything using this code. I'm 99% sure my formatting is correct, and I've tested the functions themselves several times. It seems to be only here that I'm getting any problems.

I apologize if this is a stupid question; I'll delete this if it is. I've also deleted/modified code extraneous to the issue, if the way this is organized seems strange.

Using fgets:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

char name[50];
char yesno;

void sleep() {
    printf("Try again?    (y/n)\n" );
    scanf("%s", &yesno);
    if (yesno == 'y') {
        puts("Name?");

        fgets(name,50,stdin);
        printf("Name is %s\n", name);

    }
    else {
        printf("Null");
    }
}

int main() {
    puts("Begin?    y/n");
    scanf("%s", &yesno);
    if (yesno == 'y') {
        sleep();
    }
}

The code compiles correctly, but when run, it leaves

Name?
Name is

once executed to that point.

Substituting scanf for fgets,

scanf("%[^\n]s", name);

and the same issue occurs. Strangely,

scanf("%s", name);

works, but obviously only scans until whitespace is reached.

SiggiSv
  • 1,219
  • 1
  • 10
  • 20
  • Sorry if that was unclear -- I wasn't mixing them; I was saying that using either scanf or fgets resulted in the same issue. Or am I misunderstanding you? – FreelancePoliceman Jun 11 '17 at 00:24
  • I advise this article on [why you should never use the function `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) – Badda Jun 11 '17 at 00:35
  • @Badda: thanks for that link. It's good reading — it will be enlightening for many people. – Jonathan Leffler Jun 11 '17 at 01:16
  • The "%s" format specifier is for strings, not for characters. Since `yesno` is a `char` passing its address with a format specifier of `%s` makes no sense. – David Schwartz Jun 11 '17 at 01:18

1 Answers1

0

you need to clear the buffer, because there is \n, when you fgets(name,50,stdin); you just read the \n of your last input,(when you put y and press enter, the enter is \n), so you need to read it first, and you read the other word second, for that, a simple way is to add getchar(); before fgets(name,50,stdin); and it works fine. But when you have a lot of char in your buffer (in another application) you can add this to clear all buffer while ((c = getchar()) != '\n' && c != EOF) { }

Ryuuk
  • 89
  • 1
  • 3
  • 14