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);
}
在for
循环中(在程序中提到) gets()
不接受第一行的任何字符,它直接要求第二行输入。为什么会这样?
最佳答案
您必须在 scanf
之后清理 stdin
,因为 scanf
没有使用换行符。
#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;
}
您还应该避免使用 gets
,它已被弃用。
关于c - 无法循环工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990089/