Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("\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;   
}
like image 891
solid.py Avatar asked Jan 18 '14 18:01

solid.py


People also ask

How do I stop scanf from going to the next line?

For a simple solution, you could add a space before the format specifier when you use scanf(), for example: scanf(" %c", &ch); The leading space tells scanf() to skip any whitespace characters (including newline) before reading the next character, resulting in the same behavior as with the other format specifiers.

How do I print %s in printf?

Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'.

Does printf automatically print a newline?

The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string.

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


1 Answers

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

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';
like image 58
prajmus Avatar answered Oct 25 '22 01:10

prajmus