How to print multiple strings(with spaces) using gets() in C? -


in c program, call gets() twice input user. first time user asked enter fullname , second time user asked enter friends fullname. however, on second call of gets() , doesn't wait input user skips on , finishes program. here complete code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h>  int main() { char fullname[30]; char friendsname[30]; char sentence[70]= ""; char gender;  printf("enter full name: "); gets(fullname);  printf("\n");  printf("%s , please enter gender(m/f)? : ", fullname); scanf("%c", &gender ); puts("\n");  if(gender =='m') { printf("mr. %s , please enter friends name:", fullname); gets(friendsname); puts("\n"); }  else if(gender =='f') { printf("mrs. %s , please enter friends name:", fullname); gets(friendsname); puts("\n"); }    strcat(sentence, "hello mr./mrs. "); strcat(sentence, friendsname ); strcat(sentence, ", " ); strcat(sentence, fullname); strcat(sentence, " considered friend. ");  puts(sentence);   return 0;   } 

here sample output:


enter full name: brad pitt

brad pitt , please enter gender(m/f)? : m

mr. brad pitt , please enter friends name:

hello mr./mrs. , brad pitt considered friend.

process returned 0 (0x0) execution time : 8.110 s press key continue.


the gets(friendsname); line being skipped , program continues on reason. can explain why happening ?

never never never never use gets. will introduce point of failure/security hole in code. no longer part of standard library. use fgets instead, aware attempt store trailing newline target buffer if there's room.

the reason gets(friendsname) being skipped have trailing newline in input stream after scanf call read gender; gets sees newline before other input , returns immediately.

one way around have scanf call consume trailing newline without assigning anything:

scanf(" %c%*c", &gender ); 

the * in second conversion specifier tells scanf read single character , discard it. also, leading blank in format string tells scanf skip on leading whitespace , read first non-whitespace character.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -