我想使用嵌套的switch語句爲用戶編寫一個菜單做選擇一些選項。第一個開關工作正常,並且嵌套的一個沒有。 在嵌套開關中,我總是以default
選項結束,用戶不能選擇。爲什麼第二個getchar()調用總是觸發我的交換機的默認情況?
看起來變量d
保持爲NULL,這就是使交換機在默認選項中結束的原因。什麼是防止用戶能夠鍵入一個字符,並從代碼分配值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);
}
編譯沒有錯誤。從終端的輸出:
[email protected]:# ./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
你是如何確定'D',一個'char',具有價值'NULL'? –
我打印它並得到:(null) – ic205
然後你打印不正確。你用過'%s'嗎?這是爲了字符串,而不是字符。要打印字符值:'printf(「d ='%c'\ n」,c);'將其打印爲整數:'printf(「d =%d \ n」,d);'。 –