Search code examples
cmultidimensional-arrayfgetsnull-terminated

wrapper function in fgets()


I seek for an expert in c programming. Thanks in advance.

Example:

#include <stdio.h>
#include<stdlib.h>
#include<ctype.h>

void main()
{
char name[100][52],selection[2]="Y";
int x,nname=1;
float sales;

do
{
    printf("Enter name: ");
    fflush(stdin);
    fgets(name[nname],51,stdin); // i need put a wrapper in here
    printf("Enter sales: ");
    scanf("%f",&sales);
    if (sales<1000)
        printf("%s\tgood\n",name[nname++]);
    else
        printf("%s\tvry good\n",name[nname++]);
    printf("Enter another name?(Y/N)");
    fflush(stdin);
    fgets(selection,2,stdin);
    *selection=toupper(*selection);
}while(nname<=100 && *selection=='Y');
for(x=1;x<nname;x++)
    printf("%s\n",name[x]); // want print the result without(newline) /n

printf("END\n");
system("pause");
}

How do I print the names without being separated by new lines?


Solution

  • Just use

    printf("%s ", name[x]);
    

    instead of

    printf("%s\n", name[x]);
    

    The \n character is creating the new lines.

    Edit

    fgets apparently reads newlines into the buffer - you can strip the newline with

    name[nname][strlen(name[nname])-2] = '\0';