Some error with number of keyboard inputs occured with this code for reversing a string..

i used a two-way linked list "node" for the code::

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

void insert();
void reverse();

struct node
{
	char c;
	struct node *next;
	struct node *back;
}*start=NULL;


int main()
{	
	int n,i;
	
	printf("Enter the size of the string to be reversed\n");
	scanf("%d",&n);
	printf("Now enter the %d character of the string one at a time",n);

	for(i=0;i<n;i++)
	{
		insert();
	}	
	
	reverse();	

	return(0);
}

void insert()

{	
        printf("\nEnter the character:\n");
	char w;
	scanf("%c",&w);

	struct node *tmp;

	tmp=malloc(sizeof(struct node));
        tmp->c=w;
        tmp->next=NULL;
        


        if(start==NULL)
                {
                       tmp->back=NULL;
                       start=tmp;
                }

        else
                {   
                        struct node *q;
                        q=start;
                     
                        while(q->next!=NULL)
                        {
                                q=q->next;
                        }
                     
                        tmp->back=q;
                        q->next=tmp;
                }
}	


void reverse()
{
	struct node *p=start;
	while(p->next!=NULL)
        {
                p=p->next;
        }


        printf("\nThe reversed string is :\n");


        while(p->back!=NULL)
        {
                printf("\t%c",p->c);
                p=p->back;
         }
}

The malloc function is declared in stdlib.h not malloc.h...and scanf with %c wont skip over whitespace like the newlines that get carried over during input.

1 Like

Thanku for pointing out the part causing the problem with the input count...but can u suggest a way to overcome the problem..i couldn't get through it..n a little more on this behaviour of "scanf()" will also be helpful..

Just replace the %c with %1s and that will take care of scanf reading the newline in the input...

scanf("%1s", &w);

And here is an excerpt from the scanf man page...

c                      A character is expected; the corresponding argument
                       should be a character pointer.  The normal skip-
                       over-white-space is suppressed in this case; to read
                       the next non-space character, use %1s.  If a field
                       width is given, the corresponding argument refers to
                       a character array; the indicated number of characters
                       is read.
1 Like

How about just:

char buf[64], c;
buf[0] = '\n';

while(buf[0] == '\n') // Ignore blank lines
{
        printf("Enter a character then ENTER:\n");
        fgets(buf, 64, stdin); // read entire line
}
c=buf[0];

don't use scanf if you don't need scanf, it's usually overkill and causes input buffering problems anyway.