Erica
Erica

Reputation: 3

C: Printing Linked List Problem

I'm having a bit of a problem when it comes to printing out this linked list.

The program is supposed to take a list of 10 characters from the user and print it out in the order it got it and then in reverse order (haven't got that far yet). However, it's not reading the first character.

For Example

"Please enter characters" User types a (program doesn't read the a) b c d e f g h i j k

then it prints b c d e f g h i j k

Tried to make this as detailed as possible.

Thanks!!

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

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
}RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i;
    double result;
    RECORD *head, *p;
    head=NULL;
    result=10;

    for (i=1; i<=result; i++)
        head=insert (head);
    print (head, result);

    return 0;

}

RECORD* insert (RECORD *it)
{

    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &junk);
    scanf("%s", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL;

    if (it==NULL)
        it=cur;

    else
    {
        q=it;
        while (q->next!=NULL)
            q=q->next;
        q->next=cur;
    }
    return (it);

}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;
    for(i=1;i<=j;i++)
    {
        printf("%s \n", cur->fname);
        cur=cur->next;
    }
    return;
}

Upvotes: 0

Views: 440

Answers (3)

Daniel
Daniel

Reputation: 6775

Also, notice that when you do read in that first character, I am pretty sure that it will ignore the 'k' because you are only telling it to print 10 characters, and you are giving it 11.

Finally, it is common coding practice to start loops at 0 and go until < target. For example, instead of

for (i=1; i<=result; i++)

PLEASE use

for (i=0; i<result; i++)

This is an important habit to get into because most things that you will be indexing start with index 0. It also makes your code far more readible for programmers who almost never see <= in for-loops. Notice that the two sets of conditions loop the same number of times.

Upvotes: 1

pmg
pmg

Reputation: 108986

Not taking into account the other errors, your immediate problem is an extra scanf. The junk character is the one that gets ignored.

printf("Enter a character:");
scanf("%c", &junk);
scanf("%s", &first);

Also, crank up the warning level of your compiler, and mind the warnings

Upvotes: 0

mah
mah

Reputation: 39847

However, it's not reading the first character. You're reading it and discarding it. See scanf("%c", &junk);

Upvotes: 0

Related Questions