I am getting comfortable with the foundations of C:-
There are two iterations of scanf() in this program. The first is fully functional. The second appearance does nothing and instead quits the program and returns to the standard command prompt line.
Also, my second for loop only prints the first 4 numbers instead of 5.
Here is the code :
int main() {
int i;
int iNum[4]
int iMenu = 0;
printf("\n\n\tPlease enter five numbers: ");
for (i = 0; i < 4; i++) {
scanf("%d ", &iNum[i]);
}
printf("\n\tThank you. Here are your numbers: \n\t");
for (i = 0; i < 4; i++) {
printf("%d", iNum[i]);
}
printf("\n\tMenu:");
printf("\n1\tSort your numbers ascending.");
printf("\n2\tSort your numbers descending.");
printf("\n3\tQuit program");
printf("\n\nWhat would you like to do?\n\tEnter your option here: ");
scanf(" %d", &iMenu);
switch (iMenu) {
case 1:
printf("\nCase1testPrint");
sortAsc();
break;
case 2:
printf("\nCase2testPrint");
sortDesc();
break;
. . .//rest of code }
As soon as the program reaches the second scanf(), the program ends and returns to command prompt.
This is baffling, and I have tried many variations on what could be wrong. Please provide what you may.
Here is what it looks like if I run the program. Notice my entry "1" appears in the command line instead of the program:
C:\Users\Cortland\Documents\C projects>gcc arraysort.c
C:\Users\Cortland\Documents\C projects>a
Please enter five numbers: 3
6
5
4
5
Thank you. Here are your numbers:
3 6 5 4
Menu:
1 Sort your numbers ascending.
2 Sort your numbers descending.
3 Quit program
What would you like to do?
Enter your option here:
C:\Users\Cortland\Documents\C projects>1
答案 0 :(得分:3)
Your for
loop reads four numbers, not five.
You enter five numbers. The first four are read in the for
loop. The fifth is read by
scanf(" %d", &iMenu);
So you've entered 3 6 5 4
as the four numbers, and then 5
as the choice of what to do. You haven't shown us the entire switch
statement, but my guess is that it doesn't handle the value 5
, and that it falls through and your program terminates.
(Also, you should always check the value returned by scanf()
, and take some action if it indicates that the input operation failed.)
答案 1 :(得分:0)
有几个错误。
首先,main()函数的第二行包含语法错误 - 最后应该有一个分号。这应该可以阻止你的程序编译。
其次,即使您说您希望用户输入5个数字,您的数组和循环都使用数字4.然而,您的程序仍然允许您输入五个数字的原因是因为您的编写方式调用scanf()时的格式化字符串。而不是:
scanf("%d ", &iNum[i]);
使用
scanf("%d", &iNum[i]);
请注意格式化字符串末尾没有空格?这就是你的问题进入的地方。即使你被允许输入五个号码,程序也只存储和检查其中的四个。最后一个数字卡在输入流中 - 直到,即你下次调用scanf()。这将获取您的最后一个数字,该数字通过switch / case语句(所有情况都失败,因为您没有输入“1”,“2”或“3”),程序到达main()的末尾并且退出。命令行中的“1”来自于在程序结束时尝试输入内容。
总结:
1:添加缺少的分号
2:将iNum声明中使用的数字和for循环中的数字从4更改为
3:编辑scanf()调用,从格式化字符串中删除空格。
这解决了我的问题。