[我正在尝试制作一个需要用户输入并写入输出文件的程序,但是在多次扫描输出时遇到一个奇怪的错误。
这是我的代码:
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
谢谢
问题在这里:
fputs(initializedGameState, fp);
[initializedGameState
不是以空值结尾的字符串,因此“字符串”继续到先前的变量(bday
和animal
)。
将初始化更改为:
char initializedGameState[2]; // note that you need 2 characters
initializedGameState[0] = '1';
initializedGameState[1] = '\0';