hkbharath
hkbharath

Reputation: 327

gets not working in loop

void main(){
    char tech[30][30],fname[50];
    int tn,i=0;
    FILE *fp;

    printf("File name\n");
    gets(fname);

    printf("No of lines\n");
    scanf("%d",&tn);

    for(i=0;i<tn;i++){ //gets here will not take anything for the first line
        printf("%d",i+1);
        gets(tech[i]);
    }

    fp=fopen(strcat(fname,".txt"),"w");

    for(i=0;i<tn;i++)
        fprintf(fp,"%s\n",tech[i]);
    fclose(fp);
}

in the for loop (mentioned in the program) gets() doesn't accepts any characters for the first line, it directly asks for 2nd line input. Why is that so?

Upvotes: 1

Views: 2747

Answers (2)

Nitin kumar
Nitin kumar

Reputation: 1

you can use another scanf() function before gets() function, for example,

#include<stdio.h>

#include<stdio.h>

#include<string.h>

int main()

{

int t,x,i;

char s[101];

scanf("%d",&t);

for(i=0;i<t;i++)

{

scanf("%d",x); // you can use scanf() without ampersand (&) operator.

printf("Enter your string : ");

gets(str);

printf("\n your string is : ");

puts(str);

printf("\n");

return 0;

}

Upvotes: 0

md5
md5

Reputation: 23709

You have to clean stdin after your scanf, because scanf did not consume the newline character.

#include <stdio.h>

/* Consume characters remaining in the input stream. */
void clean_stdin(void) 
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;
}


int main(void)
{
    int tn;

    /* ... */

    scanf("%d", &tn);
    clean_stdin();

    /* ... */

    return 0;
}

You should also avoid gets, it is depreciated.

Upvotes: 2

Related Questions