c - 如果我输入字母,这个 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);
}
解决方案
问题是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
语句和strcmp
from string.h
推荐阅读
- html - 带跨度的 PrimeNG 下拉菜单
- python-3.x - 如何在 Spyder 中运行 docx
- java - 我可以通过java将数据以json对象的形式存储在mysql数据库中吗?
- node.js - 如何在异步 Node.JS 中使用 MySQL
- mongodb - CentO 上 mongo db 安装的最大密钥大小限制
- java - 如何从数组列表中删除特定值及其下两个值基于一个条件使用迭代器而不是arraylist?
- linux - centos编译软件时出错?
- excel - 搜索整数的因数及其数量
- flask - Flask 说它正在运行,但代码没有显示在浏览器中
- azure - Azure:如何将两个 VM 连接到一个公共 IP 地址