简体   繁体   中英

Program hangs on Linux and Windows, Seems to work on Mac

I wrote this code for a course.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i;
    int numbersToPrint;
    int fibonacci[50] = {0,1};
    int defaultOrCustom;

    printf("Do you want to run the default length of 15 numbers, or do you want to define your own length?\n1.Default\n2.Custom\n");
    scanf("%i", &defaultOrCustom);

    switch (defaultOrCustom){
            case 1:
                for (i = 2; i < 15; i++)
                {
                    fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
                    printf("%i, ", fibonacci[i]);
                }
            break;

            case 2:
                printf("How many numbers in the sequence do you want to print?\n");
                scanf("%i\n", &numbersToPrint);
                printf("%i", numbersToPrint);
                for (i = 2; i< numbersToPrint; i++)
                {
                    fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
                    printf("%i\n", fibonacci[i]);
                }
            break;

            default:{
                printf("Please choose a valid option:\n");
                main();
            }
    }
    return 0;
}

My problem seems to be that the program hangs in case 2 after the line:

printf("%i", numbersToPrint);

I have verified this on both Linux and Windows, and have spoken to someone who has tried it on Mac, and he says the code works.

No errors show up however.

Any ideas how to fix it?

Change:

scanf("%i\n", &numbersToPrint);

to

scanf("%i", &numbersToPrint);

See c-faq for scanf hanging with '\\n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM