【发布时间】:2016-11-24 08:11:40
【问题描述】:
我正在用 C 语言创建一个菜单驱动程序,我必须要求用户输入,然后在我的程序中只使用输入的第一个字符。除了下面的代码之外,我还尝试了#define MAX_CHAR 1 并在while 循环中使用它而不是EOF 等等。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_menu();
void uppercase(char *string);
int main()
{
char i = 0, c = 0;
char selection[0];
print_menu();
while((c = getchar()) != EOF)
{
selection[i++] = c;
selection[i] = '\0'; //insert NULL at end of string
uppercase(selection);
switch(selection[i])
{
case 'c':
uppercase(selection);
printf("%s\n", selection );
print_menu();
break;
case 'X':
printf("The program is exiting, Schuss!\n" );
exit(0);
default:
printf("\nYou entered: %s\n", selection);
print_menu();
break;
}
}
return 0;
}
void print_menu() //gives code for menu
{
printf("Select a menu item and hit enter: \n" );
printf("C) Convert the string to uppercase\n");
printf("M) Display this menu\n");
printf("X) Exit the program\n");
}
void uppercase(char *string)
{
int c = 0;
while (string[c] != '\0')
{
if (string[c] >= 'a' && string[c] <= 'z')
{
string[c] = string[c] - 32;
}
c++;
}
}
如果我在运行程序时输入Yes!,我希望输出是
You entered: Y然后打印菜单。
目前的输出是
You entered: Y
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: YE
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: S
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: S!
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered:
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
^C
我很确定这是while 循环的问题,但还没有弄清楚如何解决它。最终我会有更多的菜单项和案例。因此,例如,用户将输入A,它将打印a,然后再次打印菜单以等待下一个菜单选择,直到用户输入“X”退出。另外,我知道uppercase 有两个函数调用,此时这是有意的。
编辑:我希望getchar() 按照设计的方式读取一个字符。然后做任何与该字符的大小写匹配的事情。然后再次打印菜单(这部分包含在每个 case 语句中)。然后从第 1 步开始重复(即“读取一个字符”)。
我更改了我的代码,将getchar() 放在while 循环之外,并将循环设置为while(1),而不是只读取一个字符,但也会创建一个无限循环打印You entered: B 和菜单。这就是进步,有点。
【问题讨论】:
-
char selection[0];是错误的。和switch(selection[i])-->switch(*selection) -
我尝试了不同的尺寸,但结果相同。我认为限制数组的大小会起作用,所以保持原样,因为其他大小不起作用。
-
您想读取用户输入的整行,然后只使用第一个字符。
fgets适合读取一行输入。 -
为了便于阅读和理解:1) 一致地缩进代码。仅使用空格进行缩进。 2) 遵循公理:每行只有一个语句,并且(最多)每条语句有一个变量声明。
-
虽然“隐式转换”可能允许您发布的代码正确运行,但这一行:
char i = 0 c = 0;正在尝试使用int值初始化几个char变量。建议使用:= '\0'(一个字符)作为初始化器。
标签: c arrays switch-statement getchar