'i cant enter number of times i can input name through keyboard, it skips the name entered

when i enter number of times i want enter names it skips the names that are to be entered.this prog only work if i enter number of time i want to enter names in the progam but not by input through scanf

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    char name[100],*a,*s[5] ;
    int len,i,num;
    printf("how many names you want to enter ? : ");
    scanf("%d",&num);//PROBLEM : after entering num it skips the name i want to enter and prog ends
    for(i=0;i<num;i++)
    {
       printf("Enter a name : ");
       scanf("%[^\n]%*c",name);//becoz scanf can't take 2 words,space is taken as end of string 
       len = strlen(name);
       a = (char*) malloc (len+1);
       strcpy(a,name);
       s[i] = a;
    }
}


Solution 1:[1]

Just add a blank in the format string like

scanf( " %[^\n]", name );
       ^^^

This allows to skip leading white space characters.

Or it would be even better to write

scanf( " %99[^\n]", name );
     

Pay attention to that you need to check that the entered value of num is not greater than 5 due to the declaration

char name[100],*a,*s[5] ;
                  ^^^^^

Also you should free all the allocated memory when it will not be required any more.

Another approach is to use everywhere in the program the function fgets and for entered integers to use the function atoi or strtol to convert a string to an integer.

For entered strings you should remove the new line character that can be appended by the call of fgets.

For example

fgets( name, sizeof( name ), stdin );
name[ strcspn( name, "\n" ) ] = '\0'; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1