-2

I have learnt a few languages in the past and I thought it would be a good I idea to learn C.

I am having a little trouble with scanf...

here is the code:

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


int main(){

    char name[20];
    char yn;

    printf("Welcome to Benjamin's first C programme! \n\n");

    printf("What is your name? \t"); scanf("%s", name); printf("\n");
    printf("Is your name %s? [y/n]", name); scanf("%s", yn);

}

I am having trouble with: scanf("%s", yn)

alk
  • 69,737
  • 10
  • 105
  • 255
  • Consider `char yn[2]; scanf("%1s", yn);`. The biggest road block learners have is not realizing that '\n' is not typically consumed until the next `scanf()`. Recommend to look into `fgets()/sscanf()` for user IO. – chux - Reinstate Monica Nov 26 '13 at 19:39

4 Answers4

2

do the following:

printf("Is your name %s? [y/n]", name); scanf("%c", &yn);

What the new scanf does is says "expect a char" and put it in the address of yn

Scotty Bauer
  • 1,277
  • 9
  • 14
2

To read into a char use

scanf("%c",&yn);
Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30
1

scanf() can only take pointers as parameters. name is an array so its a pointer by definition, but yn is not. You have to cast it as &yn, a pointer to yn, in order to make scanf() read to it.

Also, yn can only hold a single char, not an array of chars as in name, so you have to tell scanf() you want to read a %c for single char, not a %s for null-terminated string, because if you do you will most likely overwrite the stack and run in trouble.

That being said, use scanf("%c", &yn); instead.

Havenard
  • 27,022
  • 5
  • 36
  • 62
0

or prepare yourself and do a simple malloc (but that's not the better choice)

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


int main(){

    char name[20];
    char *yn;
    yn = (char*) malloc(sizeof(char)*2);
    printf("Welcome to Benjamin's first C programme! \n\n");

    printf("What is your name? \t"); scanf("%s", name); printf("\n");

    printf("Is your name %s? [y/n]", name); scanf("%s", yn);

}
AndreDurao
  • 5,600
  • 7
  • 41
  • 61