c-如何设置if语句选项,使其在我选择2时工作



在这段代码中if语句给我带来了问题。每当我尝试选择选项2时,它都不会给我一条消息:已选择2?如何使工作这个if语句有效?

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void hello(){
int option;
static const char * listing[] = {"Name", "Date of birth","ID card number"};
FILE * fr3 = fopen("file.txt","r");
if (fr3 == NULL) {
perror("Unable to read text file.");
exit(0);
}
for (option = 1; option <= sizeof(listing)/sizeof(char *); ++option)
printf("%d. Your %sn", option, listing[option-1]);  
fputs("Select your choice to update: ", stdout);   
if (scanf("%d", &option) == 1) {
puts("selected 1");
fclose(fr3);
exit(0);
}
if (scanf("%d", &option) == 2) {
puts("selected 2");
fclose(fr3);
exit(0);
}
fclose(fr3);
}
int main(){ hello(); }

我已将scanf("%d", &option)移位到if语句之外。因此,请检查以下代码:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void hello(){
int option;
static const char * listing[] = {"Name", "Date of birth","ID card number"};
FILE * fr3 = fopen("file.txt","r");
if (fr3 == NULL) {
perror("Unable to read text file.");
exit(0);
}

for (option = 1; option <= sizeof(listing)/sizeof(char *); ++option)
printf("%d. Your %sn", option, listing[option-1]);  

fputs("Select your choice to update: ", stdout);   
scanf("%d", &option);
if (option == 1) {
puts("selected 1");
fclose(fr3);
exit(0);
}
if (option == 2) {
puts("selected 2");
fclose(fr3);
exit(0);
}
fclose(fr3);
}
int main(){ hello(); }

最新更新