Rajdeep Sahoo
Rajdeep Sahoo

Reputation: 77

Issue with scanf() function in c?

#include<stdio.h>
void main()  
 {  
  int i;  
   char a[20];   
   char b[20];   
   scanf("%d",&i);  
    gets(a);   
    puts(a);  
gets(b);  
puts(b); 

}

Here,after entering the value of 'a' it is printing the value of i and a.It is not taking the value of 'b'.How i can insert the value of 'b'?

Upvotes: 1

Views: 54

Answers (2)

ameyCU
ameyCU

Reputation: 16607

  gets(a);   

Don't use gets it is evil. Try fgets

#include<stdio.h>
int main()   //declare here `int main()`
 {  
     int i;  
     char a[20],c[10];   
     char b[20];   
     fgets(c,sizeof c,stdin);
     i=atoi(c);         
     fgets(a,sizeof a,stdin);   
     puts(a);  
     fgets(b,sizeof b,stdin);  
     puts(b); 
     return 0;
 }

Upvotes: 0

Arkku
Arkku

Reputation: 42149

1) Never use gets, it has been removed from the C standard, and is unsafe. Use fgets instead, (e.g., fgets(a, sizeof a, stdin);). Note that fgets doesn't remove the newline from the end of the string.

2) The return type of main is int, not void.

3) The scanf does not consume the newline after reading i, so gets(a) results in a being the empty string because it reads the newline that was buffered from when the user pressed return after typing the number. Then gets(b) reads what you thought was a. (Print some prompts before reading each value and you'll see. Or try the input: 1aEnterbEnter)

Suggested solution: use fgets to read i into a buffer, then, e.g., atoi or strtol to convert it to an integer. (Or you could do an extra fgets after scanf, or getchar in a loop until you've read a newline, but, seriously, the fgets solution is a lot more robust and worth learning now.)

Upvotes: 2

Related Questions