Reputation: 163
int main(){
char str[10][50],temp[50];
int lim,i,j;
printf("Enter lim: ");
scanf("%d",&lim);
for(i=0;i<lim;++i){
printf("Enter string[%d]: ",i+1);
gets(str[i]);
}
Here the str[0](Enter string[1]: ) can't be read. The reading starts from 'Enter string[2]: '(str[1]).
But if instead of lim, an integer is passed to loop as below, program executes correctly. What may be reason for this scenario ?
int main(){
char str[10][50],temp[50];
int lim,i,j;
for(i=0;i<5;++i){
printf("Enter string: ");
gets(str[i]);
}
Upvotes: 2
Views: 83
Reputation: 26753
Your scanf()
for the number has left a newline in the input stream, which will feed the first gets()
.
Have a look here for help:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
Also, you do not want to use gets()
anymore.
Why is the gets function so dangerous that it should not be used?
Upvotes: 3
Reputation: 11921
Firstly don't use gets()
use fgets()
instead. From the manual page of gets()
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
Secondaly stdin
is line buffered, when you use scanf()
like scanf("%d",&lim);
and press ENTER
, the newline \n
char is left into stdin
stream that causes gets()
to not to read str[0]
.
For e.g
for(i=0;i<lim;++i){
printf("Enter string[%d]:\n ",i);
fgets(str[i],sizeof(str[i]),stdin);
}
Also note that when you use fgets()
it will store \n
into buffer at the end. If you don't want \n
at the end of str[index]
you have to remove it.
Also don't Forget to check the return value of fgets()
.
For e.g
char *ptr = NULL;
ptr=fgets(str[i],sizeof(str[i]),stdin);
if( ptr != NULL && str[strlen(str[i])-1] == '\n'){
str[strlen(str[i])-1] = '\0'; /* replace \n with \0 */
}
Upvotes: 2