Search code examples
cstringlinked-listprintffgets

Printing Two Strings at Same Line from using fgets()


I want to print two strings that was an input from the user using fgets(). fgets() allowed me to store strings with spaces and terminating it with an enter. Following is the example code:

fgets(tTemp ->string, 51, stdin); fflush(stdin);

Now to print it out to the screen:

printf("%s", temp->string); printf(":%s", temp->string2); 
//assuming there are 2 strings

I now want them to print on the same line with the format like this:

string:string1

however the result from the following codes were:

string

:string

how can I make the \n from fgets to not show when I print to get the format I want?


Solution

  • You have to strip it away. First get a pointer to the end, then check if it's a newline and in that case replace it with a NUL byte.

    char *eptr = tTemp->string + strlen(tTemp->string) - 1;
    
    if (eptr >= tTemp->string && *eptr == '\n')
        *eptr = '\0';
    

    The eptr >= tTemp->string is needed because you might've gotten empty string back from fgets in which case eptr would point before the start.

    You also need to check if fgets returns NULL, it's not clear if you're doing that or not. If NULL is returned the string buffer is unchanged, whatever was there before will still be there.

    Edit: Actually, reading the man page it seems empty string can't be returned. At least one character is read if NULL isn't returned. Still doesn't hurt to have the check though.