简体   繁体   中英

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) bcdefghijk

then it prints bcdefghijk

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;
}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM