【发布时间】:2019-11-25 06:51:57
【问题描述】:
在接触 Java 之后,我目前正在用 C 语言编写我的第一个程序,该程序的目的是模拟一个包含 10 个整数的堆栈。用户可以要求 push('u')、pop('o')、exit('x') 或更改输出格式。我的输出方式有一个错误,但我可以稍后处理。引起关注的主要原因是我在运行程序时得到了这个输出:
欢迎来到堆栈程序。
输入选项:u
什么号码? 1
堆栈:1
输入选项:无效字符。
输入选项:u
什么号码? 2
堆栈:1 2
输入选项:无效字符。
输入选项:u
什么号码? 3
堆栈:1 2 3
输入选项:无效字符。
输入选项:
如您所见,该程序允许我将项目压入堆栈并存储它们(pop 也可以),但每次提示用户输入新选项时,我的 switch 语句中都会出现无效字符大小写并错误地创建了一条多余的线。我知道可能需要更多的程序上下文,但我的 switch 语句有什么明显的错误吗?
#include <stdio.h>
#include <stdlib.h>
char currentOption;
int *printMode = 0;
//A program to simulate a stack data type of integers.
int main()
{
printf("Welcome to the stack program.\n");
printf("\nEnter option: ");
scanf ("%c", ¤tOption);
while(currentOption != 'x')
{
processOption(currentOption);
printf("\nEnter option: ");
scanf ("%c", ¤tOption);
}
return 0;
}
//interpret the user input character as one of several options
void processOption(char option)
{
int storedValue;
switch(option)
{
case 'u' : //push to stack
printf("What number? ");
scanf ("%d", &storedValue);
if(push(storedValue) == 1)
{
printf("Overflow!!!");
}
else
{
printf("Stack: ");
printStack(printMode);
}
break;
case 'o' : //pop, return popped value
pop(&storedValue);
if(storedValue == NULL)
{
printf("Underflow!!!");
}
else
{
printf("Popped %d", storedValue);
printf("\nStack: ");
printStack(printMode);
}
break;
case 'd' : //change print mode to decimal and print
printf("\nStack: ");
*printMode = 0;
printStack(printMode);
break;
case 'h' : //change print mode to hex and print
printf("\nStack: ");
*printMode = 1;
printStack(printMode);
break;
case 'c' : //change print mode to char and print
printf("\nStack: ");
*printMode = 2;
printStack(printMode);
break;
case 'x' : //change print mode to char and print
printf("Goodbye!");
exit(EXIT_SUCCESS);
default :
printf("Invalid character." );
break;
}
}
提前感谢您的宝贵时间!
【问题讨论】:
-
显示
main()函数或processOption()的调用者 -
'els :' 是标签语句,与 switch 语句无关。正确的格式是 ' default: ... break;
-
编译时包含所有警告和调试信息 (
gcc -Wall -Wextra -g)。使用调试器 (gdb)。阅读您正在使用的每个函数的文档。使用来自scanf的返回计数 -
^^谢谢。我修复了这个问题,因为它与我的原始问题无关,并且可能会分散“%c”问题的注意力,但感谢您的关注。
标签: c debugging stack switch-statement