在其他输入之后使用fgets()

时间:2014-05-07 19:10:40

标签: c string input char fgets

我对C编程很陌生,我在练习时遇到了麻烦。 这是我的代码:

    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);

其中rd [n]是结构数组,为地址字段分配的char []空间是100。 我知道fgets()消耗“Enter”(\ n)字符。这就是为什么当我输入phoneNum时,fgets()受到影响,我无法获得地址字段的输入。有没有其他方法可以获得长地址?

问题解决了: 我输入了

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

两次。现在它完美无缺。

1 个答案:

答案 0 :(得分:0)

#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);

}