0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "contacts.h"


int main(void)
{
int i = 0;
char middleInitial_ans;

// Declare variables here:
struct Name emp[] = { { 0 } };
struct Address addr[] = { { 0 } };
struct Numbers phone[] = { { 0 } };

// Display the title
puts("Contact Management System");
puts("-------------------------");

// Contact Name Input:

printf("Please enter the contact's first name: ");
scanf("%s", emp[i].firstName);
// PRINTING OUT FIRSTNAME
printf("%s\n\n", emp[i].firstName);

printf("Do you want to enter a middle intial(s)? (y or n): ");
scanf("%s", &middleInitial_ans); // Why doesn't the code work when I have %c instead of %s
printf("%c", middleInitial_ans);

if (middleInitial_ans == 'y') {
    printf("Please enter the contact's middle initial(s): ");
    scanf("%s", emp[i].middleInitial);
    printf("\n%s\n", emp[i].middleInitial);

So at the end I am asking the user to input a character 'y' or 'n' to see if they want to enter in their middle initial. However when I use %c since they will be entering a single character the program entirely skips this code. When I use %s instead the program recognizes the code and works fine. I am wondering why that happens?

sangmin park
  • 547
  • 3
  • 7
  • 16
  • Duplicate of so many! You still have an unread newline in the input buffer. As there are several other problems, you might want to read my [beginners' guide away from `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) –  Oct 23 '17 at 16:46

1 Answers1

0

the '&' in C is basically pass by value, variable which has capability to store the address of the memory where value is stored.

you will need bigger memory for that. like an array or buffer. %s expects the corresponding argument to be of type char *, and for scanf

char middleInitial_ans2[];

use this for %s

Sumeet
  • 9