Aether
Aether

Reputation: 11

I can't seem to figure out why scanf in my code is acting so weird

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

# define ListSize 100

typedef int DataType;
typedef struct {
DataType elem[ListSize];
int length;
}SqList;


SqList * createList(int n) 
{
    SqList *L;
    int i;
    L=(SqList *)malloc(sizeof(SqList));
    L->length=0;
    printf("Input the elements:\n");

    for (i=0;i<n;i++)
    {
        scanf("%d ",&(L->elem[i]));
        L->length++;
    }
    return L;
}


void display(SqList *L)
{
    int i;
    for (i = 0; i < L->length; i++)
    {
        printf("%d\t" , L->elem[i]);
        printf("\n");
    }
    
}

int insert(SqList *L, int mark, DataType x)//Insert element x into list in the position mark
{
    int i=0;
    if(mark>L->length||mark<0) 
    return 0;
    else
    {
        for (i=L->length-1;i>=mark;i--)
        L->elem[i+1] = L->elem[i]; //move elements
        L->elem[i+1]=x; //insert
        L->length++;
        return 1;
        
    }
}

void main()
{
    int num;
    int in,loc;
    SqList *List;
    printf("Input the number of elements:");
    scanf("%d",&num);
    List=createList(num);
    printf("\n The list is: \n");
    display(List);
    printf("Please input location and element to insert into the list: \n");
    scanf("%d %d",&loc,&in);

    insert(List,loc,in);
    display(List);
}

So my assignment was to create a sequential list and insert an element into the user typed position in the list. I came up with the above code but my scanf function is acting weird. It asks me to type in the number of elements I want in the list but for some reason it takes one more input that it should. And that input actually goes to the value of variable loc. I can't seem to understand why it's working like that.

Upvotes: 0

Views: 136

Answers (1)

Outrageous Bacon
Outrageous Bacon

Reputation: 562

The problem is with the line scanf("%d ",&(L->elem[i])); in createList. Specifically, the trailing space in the format string "%d " is consuming the carriage return when you enter the first number and you must type something else for the first call to scanf to complete. So when you think you're entering the second element, you're actually still giving input to the first scanf call. For more details on spaces in scanf format string, see this answer.

How does C treat trailing spaces in scanf?

Simply remove the trailing space "%d" and it will work as you intended.

Upvotes: 1

Related Questions