Avoid '\n' when entering a string

Viewed 36

For a program i am writing i need the user to specify the size of a string and then enter said string. I'd like to use fgets:

    #include <stdio.h>

    int main() {
 
         int size;  
         
         printf("%s", "Enter string size: ");
         scanf("%d", &size);
         
         size += 1;  // suppose we want to enter "abcd", size will be 4 + 1

         char string[size];
 
         printf("%s","Enter string: ");
 
         fgets( string, size, stdin );

         for ( size_t i = 0 ; i < size - 1 ; ++i ) {

              printf("%c", string[i] );
         }
    }

This way the program terminate right after the user enters size , i think because of the character '\n' memorized in the buffer, is that correct ? How can i avoid this?

0 Answers
Related