为什么 printf() 在打印多个字符串 (%s) 时会留下换行符以及如何解决这个问题? [英] Why printf() when printing multiple strings (%s) leaves newline and how to solve this?

查看:183
本文介绍了为什么 printf() 在打印多个字符串 (%s) 时会留下换行符以及如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个接受字符串(名字/姓氏)的程序,但不是
Phil Snowken 3 岁的典型输出,而是
Phil
斯诺肯
3 岁

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("\n-------------------------");
        printf("\nPeople Data(%d remaining)\n",N-i);
        printf("---------------------------\n\n");
        printf("\nFirst Name ");
        fgets(base[i].fname,30,stdin);
        printf("\nLast Name ");
        fgets(base[i].lname,30,stdin);
        printf("\nAge ");
        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;   
}

推荐答案

fgets() 使用输入的字符串读取换行符,因此每次按回车键都会得到 \n也读入字符串(见man fgets)

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

你必须检查最后一个字符,如果它是 \n 把它改成 \0,就像这样:

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

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

这篇关于为什么 printf() 在打印多个字符串 (%s) 时会留下换行符以及如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆