1

I am supposed to create a linked list with each node having structure:

struct stack{
    char paint;
    int index;
    struct stack *next;
}
typedef struct stack s;

I am Supposed to create linked list with m nodes by reading m inputs such as:

A 7

B 2

C 1

D 4 ....

so I tried using a for loop like this which is failing and also i tried to sequential scanfs like

scanf("%c",&c);

scanf("%d",&b);

I also tried this:

for(i=0;i<m;i++)
{
    scanf("%c %d",&c,&b);
    temp=(s *)malloc(sizeof(s));
    temp->paint=c;
    temp->index=b;
    temp->next=head;
    head=temp;
    temp=NULL;
}

What am I doing wrong? I am actually scared of scanf so I usually use getchar all the time and if possible please explain how scanf works when inputting from terminal or files which have n rows of inputs. And also alternative statement of while((c=getchar())!='\n') using scanf?

ani627
  • 5,578
  • 8
  • 39
  • 45
sarat
  • 185
  • 9
  • 1
    Can you clarify *...which is failing...*? Failing in what way? – lurker Oct 10 '14 at 19:54
  • You should really check the results of your function calls; in particular make sure `scanf` returns 2 (read 2 fields). And you're not reading the whitespace after each line (add a space to the end of your format string). – Dmitri Oct 10 '14 at 20:01
  • @lurker it is going into the for loop and nothing is happening, all i can see is the terminal waiting for input – sarat Oct 11 '14 at 03:01
  • @Dmitri There is not whitespace between inputs i just seperated them here so that it looks clean .sorry for the confusion – sarat Oct 11 '14 at 03:02
  • @sarat The whitespace I was referring to was the newlines that separate each line from the next. – Dmitri Oct 11 '14 at 03:46

2 Answers2

1

Change your scanf from

scanf("%c %d",&c,&b);

to

scanf(" %c %d",&c,&b);
//     ^Add a space before %c

The problem here is scanf is reading \n after you input a character value and an integer value and then pressing enter key.

A space before % will skip white space (also \n) and it will read the next character that is not white space.

ani627
  • 5,578
  • 8
  • 39
  • 45
  • Thank you so much @1336087 skipping the white space fixed the problem, i was frantically searching for whats wrong with the code – sarat Oct 11 '14 at 03:18
  • @sarat: You are welcome :) If your problem is resolved kindly click on the tick mark and accept an answer which was useful for you. – ani627 Oct 11 '14 at 04:21
0

In scanf, %c and %1s are not the same :

  • %c reads next character, whatever it can be a space, a newline, ...
  • %1s reads next printable character

In your use case, I think you should use

scanf("%1s %d",&c,&b);

to correctly skip eventual spaces an newline

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252