Question

I am kinda new to C programming and I am having trouble while making an exercise. Here is my code:

    printf("Enter the First Name: ");
    scanf("%s", rd[input-1].firstName);

    printf("Enter the Last Name: ");
    scanf("%s", rd[input-1].lastName);

    printf("Enter the Phone Number: ");
    scanf("%d", &rd[input-1].phoneNum);

    printf("Enter the Address: ");

    fgets(rd[input-1].address, 100, stdin);

    dataWrite();
    printRecord(input-1);

where rd[n] is a structure array and the char[] space allocated for address field is 100. I know that fgets() consumes "Enter"(\n) character. That's why when I enter phoneNum, fgets() is affected and I cannot get input for address field. Is there any other way to get a long address?

Problem solved: I typed

     fgets(rd[input-1].address, 100, stdin);

twice. Now it works perfectly fine.

Was it helpful?

Solution

#include <stdio.h>

struct data
{
  char firstName[100];
  char lastName[100];
  char phoneNum[10];
  char address[100];
};

struct data rd[10];

void printRecord(int i)
{
  printf("\n");//ugh
  printf("fn: %s\n",rd[i].firstName);
  printf("ln: %s\n",rd[i].lastName);
  printf("pn: %s\n",rd[i].phoneNum);
  printf("addr: %s\n",rd[i].address);
}

int main(int argc, char** argv)
{
  int input=1;
  char buff[100];

  printf("Enter the First Name: ");
  //char * fgets ( char * str, int num, FILE * stream );
  fgets(buff, 100, stdin);
  sscanf(buff, "%s", rd[input-1].firstName);
  //Why "input-1"? keep it as just "input" and make sure it equals the correct value before entering this area

  printf("Enter the Last Name: ");
  fgets(buff, 100, stdin);
  sscanf(buff,"%s", rd[input-1].lastName);

  printf("Enter the Phone Number: ");
  fgets(buff, 100, stdin);
  //phoneNum is a string, not an integer, get it with a %s
  sscanf(buff,"%s", &rd[input-1].phoneNum); 

  printf("Enter the Address: ");
  fgets(rd[input-1].address, 100, stdin);

  printRecord(input-1);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top