我有一个程序需要用户输入,用户输入1-8的数字来决定如何对一些数据进行排序,但如果用户只是按下回车键,则执行不同的函数。我大致知道该如何做,以为我的代码可以正常工作,但当用户只是按下回车键时,我遇到了一些问题。目前我的代码如下:
//User input needed for sorting.
fputs("Enter an option (1-8 or Return): ", stdout);
fflush(stdout);
fgets(input, sizeof input, stdin);
printf("%s entered\n", input); //DEBUGGING PURPOSES
//If no option was entered:
if(input == "\n")
{
printf("Performing alternate function.");
}
//An option was entered.
else
{
//Convert input string to an integer value to compare in switch statment.
sscanf(input, "%d", &option);
//Determine how data will be sorted based on option entered.
switch(option)
{
case 1:
printf("Option 1.\n");
break;
case 2:
printf("Option 2.\n");
break;
case 3:
printf("Option 3.\n");
break;
case 4:
printf("Option 4.\n");
break;
case 5:
printf("Option 5.\n");
break;
case 6:
printf("Option 6.\n");
break;
case 7:
printf("Option 7.\n");
break;
case 8:
printf("Option 8.\n");
break;
default:
printf("Error! Invalid option selected!\n");
break;
}
}
现在我已经将if语句更改为尝试输入=="",输入==" "和输入== "\n",但这些都似乎不起作用。 如果有任何建议,将不胜感激。 目前我所看到的是,最初的if语句失败,代码跳转到else部分,然后打印默认情况。
只是为了清楚起见,我为此代码声明的变量如下:
char input[2]; //Used to read user input.
int option = 0; //Convert user input to an integer (Used in switch statement).