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;
}
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.
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 '%%'.
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.
%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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With