首页 > 解决方案 > 如果我输入字母,这个 C 程序就不能正常工作

问题描述

如果我输入数字,一切正常。如果我输入字母,程序将不再工作。我究竟做错了什么?

Ps 那我会以函数的形式连接其他程序,我希望它们能够从菜单中运行,然后再次返回选择菜单

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main ()

{
   int a;
   do {

   
   printf("Enter number of programm: \n 1) First programm \n 2) Second programm \n 3) Third programm \n ");
   scanf("%d", &a);

   switch (a){
   case 1: printf("Start My first programm \n"); break;
   case 2: printf("Start My second programm \n"); break;
   case 3:printf("Start My third programm \n"); break;
   default: printf("There is no such program \n"); break;

   }

   } while (a != -1);

}

标签: c

解决方案


问题是scanf("%d", &a)只得到数字,因为

一个。int a只能存储数字和

湾。"%d"只得到数字

要获取字母和数字输入,您可以执行以下操作:

char a[100];
fgets(a, sizeof(a), stdin); // Store input in a, read the buffer until sizeof(a), and finally read from stdin

但是,您不能在 switch 中比较字符串,因此您必须使用if语句和strcmpfrom string.h


推荐阅读