I was writing a binary search function before finishing lecture 3 because I wanted to do some practice on my own. I was using scanf, which I had looked up, as I wanted to learn how to code without the cs50.h library. This code:

printf("Size of array:  ");
scanf("%i\n", &size);
for (int i = 0; i < size - 1; i++)
    printf("Number to be added. Must be in order:  ");
    scanf("%i\n", &ton);
    searchable[i] = ton;

however, for whatever reason, asks for input randomly. After you input a number on the first scanf, it has an empty line, where you have to input a number to progress. That number is garbage and never used in the code. Here is an example output:

Size of array:  3
Number to be added. Must be in order:  1
Number to be added. Must be in order:  2
Number to be added. Must be in order:  3

The 1 had to be inputted to get it to progress. Why is that?


The problem is here:

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

The \n is causing undesirable behavior. It shouldn't be used here. Remove the line feed and the problem goes away. When the user hits enter, the scanf handles it.

More explanation here (courtesy of @curiouskiwi ) :


If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .