我正在創建一個程式,它會一直運行,直到你寫“退出”。當您輸入月份時,程式會告訴您月份名稱的順序。例如,我輸入“一月”。程式會說“一月是第一個月。”但是,這不起作用,有時我會收到記憶體參考錯誤。我嘗試將我的scanf() 切換到gets() 和fgets(),并且我還嘗試從scanf() 中洗掉& 符號。這是我的代碼:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char**argv)
{
printf("***Hello!***\n");
//char monthes[] = {"JANUARY", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
while(1 < 5)
{
char monthName[20];
printf("Please enter the name of the month: ");
fgets(monthName, 20, stdin);
//char a = toupper(monthName);
if (strcmp(toUpperCase(monthName), "JANUARY") == 0) //1
{
printf("January is the first month.");
printf("This is from the January if statement.");
}
else if (strcmp(toUpperCase(monthName), "FEBRUARY") == 0) //2
{
printf("February is the second month.");
}
else if (strcmp(toUpperCase(monthName), "MARCH") == 0) //3
{
printf("March is the third month.");
}
else if (strcmp(toUpperCase(monthName), "APRIL") == 0) //4
{
printf("April is the fourth month.");
}
else if (strcmp(toUpperCase(monthName), "MAY") == 0) //5
{
printf("May is the fifth month.");
}
else if (strcmp(toUpperCase(monthName), "JUNE") == 0) //6
{
printf("June is the sixth month.");
}
else if (strcmp(toUpperCase(monthName), "JULY") == 0) //7
{
printf("July is the seventh month.");
}
else if (strcmp(toUpperCase(monthName), "AUGUST") == 0) //8
{
printf("January is the eighth month.");
}
else if (strcmp(toUpperCase(monthName), "SEPTEMBER") == 0) //9
{
printf("September is the nineth month.");
}
else if (strcmp(toUpperCase(monthName), "OCTOBER") == 0) //10
{
printf("October is the tenth month.");
}
else if (strcmp(toUpperCase(monthName), "NOVEMBER") == 0) //11
{
printf("November is the eleventh month.");
}
else if (strcmp(toUpperCase(monthName), "DECEMBER") == 0) //12
{
printf("December is the twelfth month.");
}
else if (strcmp(monthName, "exit") == 0)
{
printf("Bye!!!");
exit(0);
}
else
{
printf("Unknown month.");
}
}
return 0;
}
void toUpperCase(char word[])
{
int i = 0;
char chr;
while (word[i]) {
chr = word[i];
//printf("%c", toupper(chr));
i ;
}
}
uj5u.com熱心網友回復:
您的toUpperCase函式應如下所示:
char *toUpperCase(char *word)
{
for (int i = 0; word[i]; i ) {
word[i] = toupper(word[i]);
}
return word;
}
uj5u.com熱心網友回復:
所有好的評論。“while(1 < 5)”是一個有趣的無限回圈結構。功能完善,但通常使用“while (1)”或“for (;;)”。
uj5u.com熱心網友回復:
請注意,假設您對 toUpperCase() 進行了建議的更改,您的“退出”測驗將始終失敗,因為您的 monthName 緩沖區始終轉換為大寫。在第一個“JANUARY”strcmp() 之后沒有必要繼續呼叫它。你需要去掉 fgets() 留下的換行符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441992.html
上一篇:IF陳述句不一致
下一篇:緩沖區中的memcpy復雜結構
