接触 Java 之后,我目前正在用 C 编写我的第一个程序,这个程序的目的是模拟一个包含 10 个整数的堆栈。用户可以要求推送 ('u')、弹出('o')、退出('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()
中更改:
scanf ("%c", ¤tOption);
到
scanf (" %c", ¤tOption);
原因是在第一个输入后输入的杂散换行符立即被紧随其后的 scanf()
消耗。
要解决此问题,请在转换说明符前使用空格。
%c
前缀的空格告诉 scanf()
跳过第一个杂散字符,只处理之后输入的字符。
关于C switch 语句错误常规大小写和默认命中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205708/