Why not taking all inputs?

i have made this program for circular linked list. while printing stored data, it is not giving all inputs correctly. please tell me the changes to do in this program as fast you can.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>


struct list {
        char ch;

        struct list *next;
};

int main()
{
        struct list *rear;
        struct list *front;
        struct list *node;
        int n;
        char str;
        int i;

        rear = front = NULL;

        printf ("Enter value of N : ");
        scanf ("%d", &n);

        while (1) {
                scanf ("%c", &str);

                if ( str == '0' )
                        break;

                node = (struct list*) malloc (sizeof(struct list));
                node->ch = str;

                if ( rear == NULL || front == NULL ) {
                        rear = node;
                        front = node;
                } else {
                        rear->next = node;
                        rear = node;
                }
        }

        rear->next = front;

        printf ("%d\n", n);

        for ( i = 0; i < 10; i++ ) {
                printf ("%c\n", front->ch);
                front = front->next;
        }

  return 0;
}

thanks
We won't just fix it for you, but we'll help you figure it out.

Just by looking at the code, it looks very close. I'm guessing the problem is that your scanf() is accepting carriage returns so every other node in your list is a carriage return.

yes i know this is happening
but i am unable to troubleshoot it
pls help me sir
I don't understand: are you saying that you know you are putting carriage returns in the list and just don't know how to avoid doing that?

I don't have a compiler installed on this windows box so I can't compile and run your code to see what is going on.

If the above is correct, then you could do one of two things: either check to see if str == '\n' and don't insert if it is, or at the end of the loop you have to read in the carriage return and ignore it. (In the latter case, what do you want the desired behavior to be if the user enters multiple characters on a single line?)
thanks jsmith
great
Instead of checking for '\n' at each input you can try putting fflush(stdin); just before the input statement. It clears the input buffer before considering the character to be accepted.
Topic archived. No new replies allowed.