Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c - Why printf() when printing multiple strings (%s) leaves newline and how to solve this?

I made a program which accepts strings (first/last names) but instead of a typical output of
Phil Snowken age 3 , i am getting
Phil
Snowken
age 3

#include <stdio.h>
#define N 10
struct data{
char fname[30];
char lname[30];
int age;
};

main()
{
    int i;
    struct data base[N];
    for(i=0;i<N;i++){
        printf("
-------------------------");
        printf("
People Data(%d remaining)
",N-i);
        printf("---------------------------

");
        printf("
First Name ");
        fgets(base[i].fname,30,stdin);
        printf("
Last Name ");
        fgets(base[i].lname,30,stdin);
        printf("
Age ");
        scanf(" %d",&(base[i].age));
        fflush(stdin);
    }

    for(i=0;i<N;i++)
        printf("%s %s Year:(%d)",base[i].fname,base[i].lname,base[i].age);
    return 0;   
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

fgets() reads newlines with the string entered, so each time you press enter it gets the also read into string (see man fgets)

You have to check the last character and if it's change it to , like that:

size_t length = strlen(base[i].fname);
if (base[i].fname[length-1] == '
')
    base[i].fname[length-1] = '';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...