char name[20];
printf("What is your name : ");
scanf("%s",name);
char user_grade;
printf("\nEnter your grade");
scanf("%c", user_grade);
switch(user_grade){
case 'A':
printf("%s you have passed the exams with great grade !",name);
break;
case 'B':
printf("%s you have passed the exams with good grades!",name);
break;
case 'C':
printf("%s you have passed the exams with nice grades!",name);
break;
case 'F':
printf("%s sorry you have failed the exam..");
break;
default:
printf("sorry your grade are invalid. retry again by typing valid grades");
break;
}
所以代碼必須詢問用戶他們的姓名和成績,并檢查他們是否通過了考試,但代碼沒有輸入成績并輸出結果
uj5u.com熱心網友回復:
嘗試 scanf(" %c", &user_grade);
兩個更改,在前面放一個空格,%c這樣它會丟棄任何前導空格,并傳遞變數的地址,&以便函式可以更改變數。
scanf期望每個輸入項的引數指標。name是一個指標,因為您將它宣告為一個陣列(盡管您可能會在那里收到編譯器警告)。
uj5u.com熱心網友回復:
主要問題是您user_grade按scanf("%c", user_grade);值傳遞。您需要通過參考傳遞它,使用&:scanf("%c", &user_grade);
char name[20];,您確定名稱長度不超過 20 個字符嗎?如果有人輸入了一個超過 20 個字符的名稱怎么辦?:
scanf("%s",name);只會將其寫入陣列,而不管陣列的大小,您的程式將崩潰。所以,使用fgets(name, sizeof name, stdin);. 但是這里有一個問題,fgets()也回傳換行符0x0A/ \n,所以你需要使用name[strcspn(name, "\n")] = '\0';.
在此處的某些情況下,可能需要一個fflush(stdin);after 。fgets()
接下來,您需要user_grade通過參考來傳遞變數scanf(),因為它需要user_grade寫入它的記憶體地址。使用scanf(" %c", &user_grade);.
這里:信用轉到@littleadv:丟棄前導空白使用: scanf(" %c", &user_grade);
對于printf()交換機內部的所有呼叫,最好在\n每個字串的末尾添加一個以在螢屏上列印。
因此,您的最終代碼將是:
char name[20] = {}; // initialize to be safe
printf("What is your name : ");
if (fgets(name, sizeof name, stdin) == NULL) {
// check for errors
puts("ERROR reading input!");
exit(1);
}
name[strcspn(name, "\n")] = '\0'; // needs <string.h>
char user_grade = '0'; // initialized to 0, maybe not needed; I would be on the safe side
printf("\nEnter your grade: ");
scanf(" %c", &user_grade); // pass by reference using `&`
switch (user_grade) {
case 'A':
printf("%s you have passed the exams with great grade !\n", name);
break;
case 'B':
printf("%s you have passed the exams with good grades!\n", name);
break;
case 'C':
printf("%s you have passed the exams with nice grades!\n", name);
break;
case 'F':
printf("%s sorry you have failed the exam..\n", name);
break;
default:
printf("sorry your grade are invalid. retry again by typing valid grades\n");
break;
}
此外,您可以使用switch (tolower(user_grade)) {( tolower()from <ctype.h>) 允許用戶輸入小寫等級,例如a并且仍然被接受。
編輯:
@DavidC.Rankin建議我使用fgets而不是scanf避免\n被遺留并導致回圈問題,所以在這里我們可以使用它而不是scanf(" %c", &user_grade);:
char user_grade[1024] = {};
fgets(user_grade, 1024, stdin);
for (int i = 0; i < strlen(user_grade); i ) {
if (user_grade[i] != ' ' && user_grade[i] != '\t') {
// do the switch here
break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419673.html
標籤:
上一篇:系統呼叫如何讓父母等待孩子
