Thread: Unwanted line after printing string on console and also writing it to file

  1. #1
    Registered User
    Join Date
    Dec 2019
    Posts
    10

    Unwanted line after printing string on console and also writing it to file

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char name[25];
        char surname[25];
        File* F = fopen("string test.txt","w");
    
        if(F == NULL)
        {
             printf ("Error Creating File. ");
             exit(1);
         }
    
         printf("Enter name: ");
         fgets(name,24,stdin);
    
         printf("Enter surname: ');
         fgets(surname,24,stdin);
    
         //Here's the first problem:
         printf("\n\nName is: %s and Surname is: %s",name,surname);
    
        //Here's the second problem
        fprintf(F,"Name :%s and Surname :%s",name,surname);
    
        fclose(F);
    
        return 0;
    
    }
    After running the above code, I enter name "dog laptop" and Surname "hen pen" (without quotes).

    In file and on console, I get output:

    Name is: dog laptop
    and Surname is: hen pen

    My question is why did the cursor go to next line where as I didn't include a new line character?? And how to prevent this.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    fgets includes the newline character in the string that it reads. Here's one way of getting rid of it. BTW, the size value passed to fgets should be the entire size of the array, which can be found with sizeof.
    Code:
    fgets(name, sizeof name, stdin);
    size_t len = strlen(name);
    if (len > 0 && name[len - 1] == '\n')
        name[--len] = '\0';
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Dec 2019
    Posts
    10
    Wow, thanks.
    That does it.

  4. #4
    Registered User
    Join Date
    Dec 2019
    Posts
    10
    Does this mean fgets() does not initially include the NULL character?

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    No. It does include the nul character, after the newline. Otherwise we wouldn't be able to use strlen on it since strlen counts the number of characters until it hits the nul character.
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. unwanted inverted triangle in console text
    By jeremy duncan in forum C++ Programming
    Replies: 4
    Last Post: 05-13-2016, 11:32 PM
  2. Unwanted Line
    By lukesowersby in forum C Programming
    Replies: 5
    Last Post: 03-25-2009, 08:34 AM
  3. writing a Multi-Line string
    By cornacum in forum C Programming
    Replies: 3
    Last Post: 02-22-2009, 09:53 AM
  4. Writing hex nums from console input to string
    By Hawkin in forum C Programming
    Replies: 5
    Last Post: 10-17-2007, 02:39 PM

Tags for this Thread