输入多次写入输出文件(C)

问题描述 投票:0回答:1

[我正在尝试制作一个需要用户输入并写入输出文件的程序,但是在多次扫描输出时遇到一个奇怪的错误。

这是我的代码:

void firstTime(){


char name[20], animal[30], bday[8];
  char initializedGameState[1];
  initializedGameState[0] = '1';
  printf("Hello and welcome to the program! Please complete this quick first time setup.\n");
  printf("Please enter your name:\n");
  scanf("%s", &name);
  printf("\nPlease enter your birthdate (formatted MMDDYYYY):\n");
  scanf("%s", &bday);
  printf("\nHello %s, please choose a favorite animal:\n", name);
  scanf("%s", &animal);

  printf("\n");

  FILE *fp;
  fp = fopen("persistence.txt", "w");
  if(fp == NULL) printf("persistence.txt has failed to open.");
  else{
    fputs(name, fp);
    fputs("\n", fp);
    fputs(bday, fp);
    fputs("\n", fp);
    fputs(animal, fp);
    fputs("\n", fp);
    fputs(initializedGameState, fp);
    fputs("\n", fp);
    fclose(fp);
    printf("First time setup complete. Initializing Detox.me...\n");
    setGameState(1);
  }
}

但是在输入之后,这是输出:

john
04011998dog
dog
104011998dog

应为:

john
04011998
dog
1

谢谢

c file file-io output scanf
1个回答
0
投票

问题在这里:

fputs(initializedGameState, fp);

[initializedGameState不是以空值结尾的字符串,因此“字符串”继续到先前的变量(bdayanimal)。

将初始化更改为:

char initializedGameState[2]; // note that you need 2 characters
initializedGameState[0] = '1';
initializedGameState[1] = '\0';
© www.soinside.com 2019 - 2024. All rights reserved.