1
#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'?

2
  • 3
    Mandatory notice: never use gets. It has been removed from the C standard since it is impossible to use safely. Commented Jul 25, 2015 at 7:15
  • 1
    also, don't use scanf() either – it's hard to use correctly, and almost naturally, you got it wrong. Use fgets() to read in an entire line, and parse/convert it to the appropriate data type. Commented Jul 25, 2015 at 7:29

2 Answers 2

2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

"Suggested solution: use fgets to read i into a buffer" – YES! Exactly, that's how it should be done. scanf() is stupid (as in it's hard to use correctly and is unreasonably, disproportionately rarely useful.)
0
  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;
 }

2 Comments

Thanks for the sizeof edit. =) A couple of issues remain: c should be int (as the value EOF is distinct from any char), and the switch to fgets causes the newlines to remain in a and b, which shows up as extra newlines in the output.
@Arkku Yes you are very correct .Sorry for my foolishness .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.