我有一个程序需要用户输入,用户输入数字1-8来确定如何对一些数据进行排序,但如果用户刚刚输入,则执行不同的功能。我得到了如何做到这一点的总体思路,我认为我的工作很好,但是当用户刚刚敲入回车键时,我遇到了一些问题。目前,我的代码如下:C - 读取用户输入
//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).
谢谢!每个人的建议似乎都有效,但是这澄清了我什么时候应该使用一个。 – oJM86o 2010-02-25 01:16:02