Вопрос по c – корпус переключателя не работает должным образом в C
В моей программе есть небольшая проблема.
Когда я нажимаю 2 или 3 или 4, он будет отображаться правильно, но после этого, когда я нажмите a или b или c и т. д., вместо того чтобы напечатать опцию Invalid, отобразится предыдущий результат
Как я могу это исправить?
#include <stdio.h>
#include <string.h>
typedef struct vehicle
{
char name[100];
char lice_no[25];
int vehicle_type;
char cmpny_name[100];
int menu_year;
}record;
int main(void)
{
int i,choice;
FILE *fp1,*fp2;
char oname[100];
record det,det1;
int recsize;
char c;
fp1 = fopen("record.dat" , "r+");
if(fp1 == NULL)
{
fp1 = fopen("record.dat" , "w+");
if(fp1 == NULL)
{
printf("error in opening file : \n");
return -1;
}
}
recsize = sizeof(det);
do
{
printf("\t\"enter the choice\"\n");
printf("1 : adding the record\n");
printf("2 : delete the record\n");
printf("3 : editing the record\n");
printf("4 : display the record\n");
printf("5 : exit the program\n");
fflush(stdin);
scanf("%d" , &choice);
scanf("%c" , &c);
switch(choice)
{
case 1 :
{
printf("In this add logic\n")
break;
}
case 2 :
{
printf("In this case delete logic\n");
break;
}
case 3 :
{
printf("In this case edit logic\n");
break;
}
case 4 :
{
printf("display logic\n");
break;
}
case 5 :
{
printf("exit logic\n");
break;
}
default :
{
printf("\"Invalid option\"\n");
break;
}
}
}
while(1);
return 0;
}
scanf("%c" , &c);
Для чего это? Вы никогда не используете это.
ArjunShankar
;
послеIn this add logic
линия.
Mike Kwan
fflush(stdin);
выcannot сделай это.fflush
не для входных потоков. Вы не можете "очистить" входной поток.fflush
для потоков OUTPUT (например, чтобы убедиться, что все, что вы печатаете, отправляется на терминал)
ArjunShankar
что в c, когда вы читаете символы как целые числа (scanf («% d», «выбор)»), он принимает код символов ascii, например a = 97, b = 98 c = 99 d = 100, если вы хотите прочитать a как 1 b как 2 и т. Д., Вам нужно будет добавить дополнительный код, который сообщает программе, равно ли число ascii-коду abcd или e вычесть его с 96, чтобы вы получили 1,2,3 ..
scanf("%c" , &c);
потому что функция scanf требует от пользователя нажать клавишу ввода, прежде чем он сможет сохранить символ в соответствующей переменной.
So if the compiler reads the line:
scanf("%c" , &c);
он читает ваш ввод, ПЛЮС, ВВОД.
Таким образом вынуждая функцию scanf сохранять ваш ввод, PLUS, ENTER, в вашей символьной переменной.
Было бы лучше, если бы вы использовали getche () или getch () вместо функции scanf (), и, пожалуйста, никогда не используйте:
scanf("%c" , &c);
потому что это приведет к ошибке.
Sample of usage of getche() or getch() function:
c=getche(); //waits for a keypress and stores it on a variable
c=getch(); //waits for a keypress and stores it on a variable
Разница между ними заключается в том, что getche () отображает нажатие клавиш, а getch () - нет.
Примечание: не забудьте поставить
#include<conio.h>
Добавленная информация: Если вы все еще хотите использовать функцию scanf (), просто убедитесь, что вы объявили свою любимую переменную как:
char c[20];
тогда вы можете использовать:
scanf("%s", &c);
но ваша переменная может содержать до 19 символов, как мы объявили в вашем массиве символов.
И резюме не использовать:
scanf("%c", &c);
потому что это может повлиять на другие ваши функции scanf (). :)
РЕШЕНИЕ (Предупреждение о спойлере):
#include <stdio.h>
#include <string.h>
#include <conio.h>
typedef struct vehicle
{
char name[100];
char lice_no[25];
int vehicle_type;
char cmpny_name[100];
int menu_year;
}record;
int main(void)
{
int i; //removed choice from int
FILE *fp1,*fp2;
char oname[100];
record det,det1;
char choice; //made the variable choice a character
int recsize;
char c;
fp1 = fopen("record.dat" , "r+");
if(fp1 == NULL)
{
fp1 = fopen("record.dat" , "w+");
if(fp1 == NULL)
{
printf("error in opening file : \n");
return -1;
}
}
recsize = sizeof(det);
do
{
printf("\t\"enter the choice\"\n");
printf("1 : adding the record\n");
printf("2 : delete the record\n");
printf("3 : editing the record\n");
printf("4 : display the record\n");
printf("5 : exit the program\n");
fflush(stdin);
choice = getche(); // or getch()
switch(choice) //changed the target character
{
case '1' : //changed the case from 1 to '1'
{
printf("In this add logic\n");
break;
}
case '2' : //changed the case from 2 to '2'
{
printf("In this case delete logic\n");
break;
}
case '3' : //changed the case from 3 to '3'
{
printf("In this case edit logic\n");
break;
}
case '4' : //changed the case from 4 to '4'
{
printf("display logic\n");
break;
}
case '5' : //changed the case from 5 to '5'
{
printf("exit logic\n");
break;
}
default :
{
printf("\"Invalid option\"\n");
break;
}
}
}
while(1);
return 0;
}
Вы также можете использовать переключатель для сравнения символов. Просто измените значения
case 1:
в
case '1':
conio.h
Error: User Rate Limit ExceededhaveError: User Rate Limit Exceededconio.h
Error: User Rate Limit Exceededconio.h
Error: User Rate Limit Exceededen.wikipedia.org/wiki/Conio.h