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

1
  • 1
    Because the scanf above haven't consumed the new line character - so gets will just eat the new line character instead of getting the next line.
    – nhahtdh
    Oct 20, 2012 at 15:51

2 Answers 2

2

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.

1
  • "depreciated" means gone down in value... ITYM "deprecated" however it isn't that either -- it has been removed from C entirely now
    – M.M
    Mar 1, 2015 at 12:46
0

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;

}

1
  • 1
    Welcome to Stack Overflow. Please could you edit your question and apply proper code formatting. There is a formatting guide to help you.
    – David Buck
    Oct 11, 2020 at 8:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.