得不到循环工作

时间:2012-10-20 15:49:11

标签: c

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()不接受第一行的任何字符,它直接要求第二行输入。为什么会这样?

2 个答案:

答案 0 :(得分:2)

您必须在stdin之后清除scanf,因为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,它会被折旧。

答案 1 :(得分:0)

您可以在gets()函数之前使用另一个scanf()函数, 例如,

#include

#include

#include

int main()

{

int t,x,i;

char s [101];

scanf(“%d”,&t);

for(i = 0; i

{

scanf(“%d”,x); //您可以使用不带&运算符的scanf()。

printf(“输入您的字符串:”);

gets(str);

printf(“ \ n您的字符串是:”);

puts(str);

printf(“ \ n”);

返回0;

}

相关问题