string - c programming: (scanf and gets) -
am aware difference between scanf() , gets() function scanf() continues read input string until encounters whitespace, whereas gets() continues read input string until encounters \n or eof(end of file).
to see difference in action, tried writing example on own follows:
                 #include <stdio.h>                   int main()                 {                        char a[20];                    printf("enter string\n");                    scanf("%s",&a);                    printf("the string %s\n",a);                    char b[20];                    printf("enter string\n");                    gets(b);                    printf("the string %s\n",b);                    return 0;                 } when variable given string "manchester united" input, output was:
                   enter string                    manchester united                    string manchester                    enter string                    warning: program uses gets(), unsafe.                    string  united what expecting output first part of string given variable manchester , then, program prompting me enter new input string variable b. instead, ended above given output.
based on output, understand is:
it can seen scanf() encounters whitespace, stops reading string thereafter, , thus, remaining part of string:united, has been assigned variable b,even without program prompting me enter string variable b.
how flush out remaining part(the portion after whitespace) of string given variable a?
so that, can enter whole new input string variable b.
any further explanation on happening here in execution of code appreciated.
apologies basic mistakes(as evident responses)!! novice c programming:)
you can flush manually reading , discarding characters until find '\n' or hits appropriate key combination cause eof. or can ask scanf() discard until '\n' found, second 1 can achieved this
char string[20]; scanf("%19s%*[^\n]\n", string); there other things code, wrong
- you declare - aarray of 20- char, pass it's address- scanf()expects pointer of- char, array name (the variable if prefer) automatically converted pointer- charwhen it's necessary.
- you used - gets(), it's old dangerous , deprecated function no longer standard function. should use- fgets()instead takes parameter perevent overflowing destination array.
this example testing suggested fixes
#include <stdio.h>  int main(void) {         char string[20];      string[0] = '\0'; /* avoid undefined behaviour                           when passing `fprintf()' */      scanf("%19s%*[^\n]\n", string);     fprintf(stdout, "%s\n", string);      fgets(string, sizeof(string), stdin);     fprintf(stdout, "%s\n", string);      return 0; }