Home > OS >  printf goes to new line where it shouldn't
printf goes to new line where it shouldn't

Time:12-02

when i launch this 2 lines of code

printf("|%-16s|%-16s|%-16d|\n","name","surname", 30);
printf("|%-16s|%-16s|%-16d|\n", database_publishers[pointer1].name, database_publishers[pointer1].client, database_publishers[pointer1].price);

it gives me output like this:

|name            |surname         |30              |
|name
           |surname
        |30              |

image:
image

variables in second printf call were got from user in other function, using fgets call like this

fgets(database_publishers[pointer].name, STRING_SIZE, stdin);

there are no any \n in this function and i have no idea why does it print every variable in new line. btw i work in visual studio, maybe it matters, idk, im just a rookie in programming

CodePudding user response:

Text that is read using fgets does most-likely contains a newline at the end. You can test for this and remove it if required. Try to add the following piece of code before you try to print out the result:

size_t length = strlen(database_publishers[pointer].name);
if(database_publishers[pointer].name[length - 1] == '\n')
    database_publishers[pointer].name[length - 1] = '\0';

Also, see this question, the above is basically this awnser.

Otherwise, if there is a newline character, your output will look like this:

|name            |surname         |30              |
|name<newline>
<remaining whitespace> | <...>

CodePudding user response:

I added this:

database_publishers[pointer].name[strcspn(database_publishers[pointer].name, "\n")] = 0;
database_publishers[pointer].client[strcspn(database_publishers[pointer].client, "\n")] = 0;

after fgets calls and now it works like it should i've found it here: Removing trailing newline character from fgets() input

CodePudding user response:

You are using "\n" in the program. Try removing it

  •  Tags:  
  • c
  • Related