一、题目
本实验2是基于实验1的基础,当用户根据系统的提示输入相应的字母时,系统根据用户的选择,输出相关信息。
具体要求:
当用户输入I时,系统输出 You are trying to input info
当用户输入O时,系统输出 You are trying to output info
当用户输入D时,系统输出 You are trying to make things ordered
当用户输入Q时,系统输出 You are about to quit
二、代码
#include <stdio.h>
#include <string.h>
int main(){
char a[256];
scanf("%s",&a);
if(strcmp(a,"I")==0){
printf("You are trying to input info");
}
if(strcmp(a,"O")==0){
printf("You are trying to output info");
}
if(strcmp(a,"D")==0){
printf("You are trying to make things ordered");
}
if(strcmp(a,"Q")==0){
printf("You are about to quit");
}
return 0;
}
#include<stdio.h>
int main(){
char mychoice;
scanf("%c",&mychoice);
switch (mychoice){
case 'I':
printf("You are trying to input info");
break;
case 'O':
printf("You are trying to output info");
break;
case 'D':
printf("You are trying to make things ordered");
break;
case 'Q':
printf("You are about to quit");
break;
}
return 0;
}
三、tips:
strcmp函数
比较两个字符串
if(strcmp(str1,str2)==0){
printf("相同");
}
第一个字符串acsll码大于第二个字符串,则返回大于0的数字
第一个字符串等于第二个字符串,则返回0
第一个字符串小于第二个字符串,则返回小于0的数字
2.switch函数
没有用switch是因为刚开始并没有分清字符与字符串,导致mychoice定义的是字符串,所以用switch函数报错
在 C 语言中,switch 语句中的表达式必须是常量表达式,且必须是整型或者枚举类型,所以 switch 语句不能直接匹配字符串。
但是因祸得福学了挺多东西
注意记得加break跳出