0

My Code is:-

/* Program to store data in link list and then print all data*/

#include <stdio.h>
#include <malloc.h>
struct value
{
    char data;
    struct value *next;
};

void main(void)
{
    struct value *head, *temp;
    char i;

    head = (struct value *) malloc (sizeof(struct value));

    temp = head;
    while (temp != NULL)
    {
        printf("Enter value to store in link list Enter z to stop\n");
        scanf("%c", &i);

        temp->data = i;
        if (i == 'z')
        {
            temp->next = NULL;
        }
        else
        {
            temp->next = (struct value *) malloc (sizeof(struct value));
        }
        temp = temp->next; 
    }

    temp = head;
    while (temp != NULL)
    {
        printf("Data is %c\n", temp->data);
        temp = temp->next;
    }

}

Output:-

Enter value to store in link list Enter z to stop
a
Enter value to store in link list Enter z to stop
Enter value to store in link list Enter z to stop
b
Enter value to store in link list Enter z to stop
Enter value to store in link list Enter z to stop
c
Enter value to store in link list Enter z to stop
Enter value to store in link list Enter z to stop
z

Data is a
Data is

Data is b
Data is

Data is
c Data is

Data is
z


Process exited after 4.95 seconds with return value 0 Press any key to continue . . .

Please tell me why its printing one statement twice. Whats wrong with the code Thanks

Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
sunny
  • 1
  • 2
  • https://stackoverflow.com/a/34459969/669576 – 001 Oct 18 '17 at 19:57
  • You're probably entering two characters at a time: The letter you type, and enter. After hitting enter, the program sees the letter, processes it, then immediately picks up the newline. Only then does it wait for you to type more. – Tom Karzes Oct 18 '17 at 20:00
  • Yes after entering first character it waits until i type z as i mentioned my code. But same program working fine for storing integer – sunny Oct 18 '17 at 20:06
  • That is because `%d` always discards leading whitespace but `%c` does not, unless you instruct it to. – Weather Vane Oct 18 '17 at 20:06
  • But i am not entering any white space, So how can i make it right ? – sunny Oct 18 '17 at 20:08
  • The newline is whitespace. Please read the duplicate before asking anything else. – Weather Vane Oct 18 '17 at 20:08

0 Answers0