c - 每当我选择 2 时,如何设置 if 语句选项以使其正常工作?
问题描述
在这段代码中,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 %s\n", 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 %s\n", 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(); }