Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';我搞不懂这个循环行为_C - Fatal编程技术网

Can';我搞不懂这个循环行为

Can';我搞不懂这个循环行为,c,C,我在做一个文件处理项目,在这个项目中,用户可以指定输入的次数,内容将以表格格式存储在一个文件中。我的代码是: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int n; FILE *fptr; fptr=fopen("input.txt", "w"); if(fptr==NULL) printf("Th

我在做一个文件处理项目,在这个项目中,用户可以指定输入的次数,内容将以表格格式存储在一个文件中。我的代码是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    int n;
    FILE *fptr;
    fptr=fopen("input.txt", "w");

    if(fptr==NULL)
         printf("The file could not be opened.");

    printf("\nFile opened successfully.");

    printf("\nHow many inputs do you want to make?");
    scanf("%d", &n);

    printf("\nEnter contents: \n\n");

    char name[50];
    int age;
    float salary;
    int i;

    for(i=1;i<=n;i++)
    {
       printf("\nName(Not more than 50 character): ");
       gets(name);

       if(name[strlen(name)-1]=='\n')
            name[strlen(name)-1]='\0';

       printf("\nAge: ");
       scanf("%d", &age);

       printf("\nSalary: ");
       scanf("%f", &salary);

       fprintf(fptr, "%s\t\t%d\t$%.2f\n", name, age, salary);
    }
}
#包括
#包括
#包括
内部主(空)
{
int n;
文件*fptr;
fptr=fopen(“input.txt”,“w”);
如果(fptr==NULL)
printf(“无法打开文件”);
printf(“\n文件已成功打开。”);
printf(“\n要输入多少个?”);
scanf(“%d”和“&n”);
printf(“\n输入内容:\n\n”);
字符名[50];
智力年龄;
浮动工资;
int i;
对于(i=1;iTry

这对我来说很有用…如果没有,请发布它给你的输出,我会尽力提供更多帮助

另外,请务必查看WhozCraig的评论,并在循环之前修复该错误。

scanf("%d", &n);
它读取数字,但不读取终止输入的换行符,将换行符留在输入缓冲区中

gets(name);
它将该换行符作为空行读取。您需要跳过上一次
scanf
调用中的所有剩余字符,包括换行符。例如,您可以有一个循环,每次读取一个字符,直到读取完换行符



作为旁注:不要使用
gets
。这很危险,自C99标准以来就被弃用了,在最新的C11标准中被完全删除。建议的替代品是
fgets

启用编译器警告,可能。投票以简单的键入方式关闭。请注意,在C99标准中没有名为
gets
的函数e C语言,它在17年前就过时了,5年前就被完全删除了。你学习C语言的来源已经完全过时了。这是一个打字错误。谢谢你指出。没有必要为此命名。@Masquerade007用
get(name);
替换为
int C;而((C=getchar())!='\n'&&C!=EOF);if(scanf(“%49[^\n]”,name)!=1)fputs(“未能扫描名称!”,stderr);
scanf(“%s”,name)不允许存储空格。我一开始就尝试了,它只存储名称的第一部分。那是因为我忽略了循环。是的,我通常不使用get(),因为它在我以前的项目中造成了很多麻烦。我从scanf(“%[^\n]s”,name)开始和fgets(name,sizeof(name),stdin),但它们不起作用,所以最终我尝试使用get(),当我在这里发布问题时,问题仍然存在于代码中。
gets(name);