首先,我想先感謝大家。我非常期待在計算機科學領域取得進展,並在我變得更加精通時幫助其他人。我的代碼循環比我想要的多一次,我懷疑我的getchar語句有問題
現在,這裏是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#define RECORDS 30
/*Questions
Formatting display() - can we use spaces to format?
Is the patient structure supposed to be global or local in enter()?
*/
void enter();
void display();
void update();
void loadDisk();
void writeDisk();
void emptyDisk();
void sort();
void clear();
struct patient
{
char * name;
int age;
double highBP, lowBP, riskFactor;
};
struct patient * db[RECORDS];
int counter = 0;
main()
{
int flag = 1;
while (flag == 1)
{
printf("---------------------------------------------------------\n");
printf("|\t(N)ew record\t(D)isplay db\t(U)pdate record |\n");
printf("|\t(L)oad disk\t(W)rite disk\t(E)mpty disk |\n");
printf("|\t(S)ort db\t(C)lear db\t(Q)uit |\n");
printf("---------------------------------------------------------\n");
printf("choose one: ");
char selection = getchar();
printf("selection %c\n", selection);
if ((selection == 'n') || (selection == 'N'))
{
//New record
enter();
}
else if ((selection == 'd') || (selection == 'D'))
{
//Display db
//printf("display %d\n", flag);
display();
}
else if ((selection == 'u') || (selection == 'U'))
{
//Update db
update();
}
else if ((selection == 'l') || (selection == 'L'))
{
//Load disk
loadDisk();
}
else if ((selection == 'w') || (selection == 'W'))
{
//Write disk
writeDisk();
}
else if ((selection == 'e') || (selection == 'E'))
{
//Empty disk
emptyDisk();
}
else if ((selection == 's') || (selection == 'S'))
{
//Sort db
sort();
}
else if ((selection == 'c') || (selection == 'C'))
{
//Clear db
clear();
}
else if ((selection == 'q') || (selection == 'Q'))
{
//Quit
flag = 0;
}
else
{
printf("not a vaild input\n");
}
}
}
void enter()
{
/*struct patient temp;
printf("name: "); sscanf("%s", temp.name);
printf("age: "); scanf("%d", temp.age);
printf("high bp: "); scanf("%f", temp.highBP);
printf("low bp: "); scanf("%f", temp.lowBP);
db[counter] = (struct patient *) calloc(1, sizeof(temp));
*db[counter] = temp;
//printf("%s, %d, %f, %f", db[counter]->name, db[counter]->age, db[counter]->highBP, db[counter]->lowBP);
counter++;*/
}
void display()
{
}
void update()
{
}
void loadDisk()
{
}
void writeDisk()
{
}
void emptyDisk()
{
}
void sort()
{
}
void clear()
{
}
我運行時遇到的問題是,菜單顯示後,我兩次輸入選項。我無法理解發生了什麼問題,但我懷疑它與存儲選擇和新行字符的getchar有關,因此運行它兩次。這也意味着最終的其他聲明將會運行,它會這樣做。
我想我已經對問題進行了三角分析,只是不確定如何解決它。先謝謝你!
僅供參考:'getchar'返回一個'int',而不是'char'。在將其重新轉換爲char字符之前,必須首先對常量EOF進行測試,以確定是否已經達到了輸入的結尾(例如,在Unix-ish終端上控制-D,或者從結束管道中的輸入或重定向文件)。你應該像對待用戶輸入'q'一樣對待它。另外,C沒有'switch'語句? – derobert