-2

For some reason my C program closes immediately after outputting "Enter a letter (D/E/F): "

I would like to be able to store 3 characters in the letters[] array so that I can print them later on.

I use Visual Studio 2017 and the program has no errors. It just seems to skips everything after printf("Enter a letter (D/E/F): ");.

I think the problem has to do with scanf_s, but I don't exactly know what the problem is or how to fix it. Here's my program:

#include <stdio.h>

int main(void)
{
    char letters[3];
    char ch;
    printf("Enter a letter (A/B/C): ");
    scanf_s(" %c", &ch);
    letters[0] = ch;
    printf("Enter a letter (D/E/F): ");
    scanf_s(" %c", &ch);
    letters[1] = ch;
    printf("Enter a letter (G/H/I): ");
    scanf_s(" %c", &ch);
    letters[2] = ch;

    printf("You entered %c, %c, and %c.", letters[0], letters[1], letters[2]);

    getchar(); getchar(); // PAUSE
    return 0;
}

Please help.

onsl
  • 1
  • 1
  • 1
    You have an argument missing, please read the man page for `scanf_s` *in detail*. It is not `scanf` so make no assumptions. – Weather Vane Nov 18 '17 at 23:44
  • 1
    You use [the `scanf_s` function](https://msdn.microsoft.com/en-us/library/w40768et.aspx) wrong. – Some programmer dude Nov 18 '17 at 23:44
  • Check out the solutions posted on this question : https://stackoverflow.com/questions/21434735/difference-between-scanf-and-scanf-s – Ahmed Karaman Nov 18 '17 at 23:45
  • 1
    *Unlike `scanf` and `wscanf`, `scanf_s` and `wscanf_s` require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.* – Weather Vane Nov 18 '17 at 23:46

1 Answers1

0

Changed scanf_s(" %c", &ch); to scanf_s(" %c", &ch, 1); and the program now works!

Thanks Weather Vane, Some programmer dude, Kal Karaman, Weather Vane again, and this webpage: http://faculty.edcc.edu/paul.bladek/CS131/scanf_s.htm!

onsl
  • 1
  • 1