Home > other >  To take an integer input after character I used " %c " but does not run when no integer gi
To take an integer input after character I used " %c " but does not run when no integer gi

Time:10-30

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

struct node
{
    int value;
    struct node *next;
};

struct node *push(struct node *head, int x)
{
    struct node *v = (struct node *)malloc(sizeof(struct node *));
    v->next = head;
    v->value = x;
    return v;
}

struct node *pop(struct node *head)
{
    return head->next;
}

void print(struct node *head)
{
    if (head == NULL)
    {
        printf("NULL\n");
    }
    else
    {
        while (head != NULL)
        {
            printf("%d", head->value);
            if (head->next != NULL)
            {
                printf(" ");
            }
            head = head->next;
        }
        printf("\n");
    }
}

int main()
{
    struct node *head = NULL;
    char c;
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i  )
    {
        scanf(" %c ", &c);
        if (c == 'a')
        {
            int x;
            scanf("%d", &x);
            head = push(head, x);
            print(head);
        }
        else if (c == 'd')
        {
            head = pop(head);
            print(head);
        }
    }
}

In the above code, I take integer input when the character input is 'a' but when the character input is 'd' I don't have to take input as I am deleting the first element of the stack. I referred this post. But now I am unable to handle the case of 'd' where I don't have to take integer input again. Please rectify my code.

Edit:

As mentioned in the replies to my query if I remove the whitespace from %c, then 'a' and 'd' mention in my code works properly but the for loop does not run 4 times instead only runs 2 times. Thus the input I and output are as follows:

4
a 1
1
d
NULL

Here, (4,a 1,d) are inputs and (1 and NULL) outputs. After printing NULL the program terminates but ideally, it should have taken two more inputs. Please rectify my code.

CodePudding user response:

The problem is the trailing spaces in your scanf formats. When a scanf format contains a space, scanf will read (and discard) whitespace characters until it gets a non-whitespace character (at which point it will leave that non-whitespace character as the next character to be read by the next pattern or call).

The net result of this is that when you have an input line like dEnter, the scanf(" %c ", call won't return until you enter another line with some non-whitespace characters (which will be left for the next scanf call to read).

Simply delete those trailing spaces in the formats and all should be fine. The leading spaces are necessary to ignore any whitespace (such a newline from a preceeding command) prior to the command character.

  •  Tags:  
  • c
  • Related