Why printf() when printing multiple strings (%s) leaves newline and how to solve this?

前端 未结 1 1316
死守一世寂寞
死守一世寂寞 2020-12-10 17:43

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

         


        
相关标签:
1条回答
  • 2020-12-10 18:50

    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';
    
    0 讨论(0)
提交回复
热议问题