2

I'm new to C language. My task is to Read and Print Struct array in a loop. I wanted to read and print using IF ELSE statement. But the program doesn't store the the previous memory I inputted. Please use printf, Scanf, and fgets. I couldn't figure out how to make the program print all the given input from the users.

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

struct Data
{
  char name[50];
};
void readData(struct Data *array);
void showData(struct Data *array);

int main()
{
  int i, j;
  int choice;

  struct Data array[2];

  printf(" 1) Read Data 2) Show Data");
  do
  {
    printf(" \n Option: ");
    scanf("%d", &choice);

    if(choice==1)
    {
      readData(array);
    }

    else if(choice==2)
    {
      showData(array);
    }
    else
    {
      printf("unkown option! \n");
    }
  }
  while(1);
}


void readData(struct Data *array)
{
  int i;
  for (i = 0 ; i < 2 ; i++)
  {
    printf("enter name: ");
    fgets(array[i].name, sizeof(array[i].name), stdin);
  }
}

void showData(struct Data *array)
{
  int i;
  for (i = 0 ; i < 2 ; i++)
  {
    printf("%s", array[i].name);
  }
}

Below is my Output:

1) Read Data 2) Show Data 
 Option: 1
enter name: enter name: dd
 
 Option: 1
enter name: enter name: ss
 
 Option: 2

ss
 
 Option: 

Thanks, much appreciate!

yano
  • 4,827
  • 2
  • 23
  • 35
Siam C.
  • 23
  • 4
  • 1
    The problem is `scanf` is leaving a newline character in the input buffer (placed there when you hit enter for your Option), then the first iteration of `fgets` reads that newline as your input. This is why it doesn't "pause" for your input the first time thru the loop and seems to skip directly to the second ("enter name:" is displayed twice). You can see when you print the names (Option 2), there's an extra newline, that's actually the first name newline from `scanf`. See https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf – yano Nov 25 '20 at 05:45
  • And always format your code,, makes it much easier to read. Any code editor will do this for you. – yano Nov 25 '20 at 06:26
  • Does this answer your question? [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) – Yunnosch Nov 25 '20 at 06:46
  • 1
    @yano Please consider flagging as duplicate in situations like this. Good find by the way. – Yunnosch Nov 25 '20 at 06:47
  • @Yunnosch Wow, all this time I thought you needed 3k rep to flag a duplicate, now I see that's what you need to cast close votes, not to flag. Thanks for bringing that to my attention. – yano Nov 25 '20 at 16:24

0 Answers0