contact entry = {"", "", "", ""};
while (choice == 1 || 2 || 3 || 4){
if (choice == 1){
printf ("First name: \n");
fgets(entry.firstname, sizeof(entry.firstname),stdin);
break;
}
else if(choice == 2){
printf ("Last name: \n");
fgets(entry.lastname, sizeof(entry.lastname),stdin);
break;
}
else if(choice == 3){
printf ("Address: \n");
fgets(entry.address, sizeof(entry.address),stdin);
break;
}
else if (choice == 4){
printf ("Phone number: \n");
fgets(entry.phone, sizeof(entry.phone),stdin);
break;
}
else{
printf("Exiting");
return 0;
}
}
fwrite (&entry, sizeof (contact), 1, pFile);
fclose(pFile);
Run Code Online (Sandbox Code Playgroud)
这是我的代码.它似乎很简单,如果按1,2,3或4,我跟踪它.所以它知道if,否则if,否则它会去,但它似乎很快就退出,并且没有写出我想要的文件.这里有任何明显的错误吗?提前致谢.
编辑1:
我改变了(choice> = 1 && choice <= 4){to while(choice> = 1 && choice <= 4){,但我仍然遇到没有写入文件的问题.pFile = fopen("C:\ contacts.txt","w +"); 是我理解的正确方法.
更改:
while (choice == 1 || 2 || 3 || 4){
Run Code Online (Sandbox Code Playgroud)
至:
while (choice == 1 || choice == 2 || choice == 3 || choice == 4){
Run Code Online (Sandbox Code Playgroud)
或者更简洁:
while (choice >= 1 && choice <= 4){
Run Code Online (Sandbox Code Playgroud)