我试图使用嵌套的开关语句为用户编写菜单,做一些选择。第一个开关工作正常,而嵌套开关不工作。在嵌套开关中,我总是在default选项中结束,用户无法选择。
似乎变量d保持为空,这就是导致开关在默认选项中结束的原因。是什么阻止用户输入char,以及阻止向d分配值的代码呢?
#include<mysql.h>
#include<stdio.h>
#include<stdlib.h>
/* function declaration */
int connection_func();
int main() {
/*make connection to sql server*/
int connection_return = connection_func();
printf("%d",connection_return);
char c,d;
printf("\n Choose one of the following options: \n");
printf("1- DB maintenance \n");
printf("2- Weekly schedule creation \n");
c= getchar();
switch(c) {
case '1':
// DB maintenance
printf("\n DB maintenance options:: \n");
printf("1- ADD data to existing table \n");
printf("2- DELETE data from existing table \n");
printf("3- DISPLAY all data inside a table \n");
printf("4- DROP table (root only) \n");
d = getchar();
switch(d) {
case 'A':
// User want to ADD data to the database
break;
case 'B':
// User want to DELETE data from database
break;
case 'C':
// User want to Display the tbl data
break;
case 'D':
// User want to DROP tables
break;
default:
printf("That is not a proper selection \n");
break;
}
break;
case '2':
// Weekly schedule creation
break;
default:
printf("That is not a proper selection. \n");
break;
}
return(0);
}
int connection_func() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "mypassword";
char *database = "sc" ;
conn = mysql_init(NULL);
/* Connect to database */
if ( !mysql_real_connect(conn, server, user, password, database, 0, NULL , 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return(1);
}
return(0);
}编译过程中没有错误。终端的输出:
root@kali:# ./sc
0
Choose one of the following options:
1- DB maintenance
2- Weekly schedule creation
1
(null) -d (**** - the value of d variable ***)
DB maintenance options::
1- ADD data to existing table
2- DELETE data from existing table
3- DISPLAY all data inside a table
4- DROP table (root only)
That is not a proper selection 发布于 2015-12-17 20:10:49
插入'1‘并单击enter后,stdin流中有"1\n“,然后调用getchar()一次,"1”已从stdin中删除。
然后,下一个对getchar()的调用不会提示用户,因为stdin流中已经有数据--换行符'\n‘。
试着使用
while((d = getchar()) != '\n' && d != EOF);要将无用的数据旋出,直到行中断,通常只有'\n‘字符,因此您甚至可以使用再次执行一个调用getchar()从流中删除换行符。
另外,正如其他评论中提到的,我认为飞碟
发布于 2015-12-17 20:06:44
请注意,您甚至没有机会说A或B。
按1之后,按Enter键。1进入c,d = getchar()导致d具有换行符代码。
https://stackoverflow.com/questions/34343232
复制相似问题