我打算在以后的函数中使用read_command。我怎样才能使我的read_command不继续打印“输入命令:”。我想在将来的if语句中使用这个函数。
#include <stdio.h>
#include <stdbool.h>
char read_command()
{
char command;
char result;
printf("Enter a command: ");
scanf("%c", &command);
if (command == 'I' || command == 'i' || command == 'P' || command == 'p' || command == 'D' || command == 'd' || command == 'L' || command == 'l' || command == 'Q'|| command == 'q')
result = command;
else
result = 'V';
return result;
}
void print_music_lib()
{
if (read_command == 'P'|| read_command == 'p')
{
printf("Only prints when case is P or p");
}
}
void evaluate_command()
{
while (true)
{
char valid_command = read_command();
scanf("%c", &valid_command);
switch(valid_command)
{
case 'I':
case 'i':
printf("This is the letter I or i\n");
case 'P':
case 'p':
printf("This is the letter P or p\n");
case 'D':
case 'd':
printf("This is the letter D or d\n");
case 'L':
case 'l':
printf("This is the letter L or l\n");
case 'Q':
case 'q':
printf("This is the letter Q or q\n");
//on_quit = valid_command;
}
if (valid_command == 'Q' || valid_command == 'q')
break;
//return on_quit;
}
}
int main()
{
read_command();
//printf("%c", read_command());
evaluate_command();
return 0;
}
答案 0 :(得分:2)
你基本上只有两个解决方案:
在调用read_command
之前,不要在函数内打印提示,而是将其打印在调用函数中。
添加一个布尔参数,告诉函数是否应该打印提示。
顺便说一句,您显示的代码中存在逻辑错误(除了语法错误):当您执行
时if (read_command() == 'P'|| read_command() == 'p')
您实际上正在读取输入两次,当然也会强制用户两次输入输入。相反,您应该将结果存储在变量中并检查变量:
char result = read_command();
if (result == 'p' || result == 'P') { ... }
顺便提一下,这也会解决提示问题:一个电话,一个提示。