【问题标题】:File processing in C; won't take inputC中的文件处理;不会接受输入
【发布时间】:2015-09-16 12:50:39
【问题描述】:

我开始学习用 C 语言处理文件。这个特定程序的重点是创建一个名为“clients.dat”的文件,我在其中存储银行客户的帐号、姓名和余额,比如说.我已经对代码进行了工作和改进,使其完美复制了教科书作为示例提供的内容,但由于某种原因,我的代码在第一个“scanf”之后无休止地循环并重新打印问号以被遗忘,而从未进入 scanf while 循环内的语句。有人会对为什么会发生这种情况有任何建议吗?我的编译器是 Netbeans,我在 Linux-Ubuntu 上运行它。

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

/*
 * 
 */
int main() {

    unsigned int actNumber;
    char actName[30];
    long double actBalance;

    FILE *fPtr;

    if((fPtr = fopen("clients.dat", "w")) == NULL) {
        printf("File could not be found.\n");
    }

    else {
        printf("Enter the Account Number, Name, and Balance.\n Hit the EoF to exit.\n");
        printf("%s","?");
        scanf("%d%29s%lf", &actNumber, actName, &actBalance);

        while (!feof(stdin)) {            
            fprintf(fPtr, "%d, %29s, %.2lf\n", actNumber, actName, actBalance);
            printf("%s", "?");
            scanf("%d%29s%lf", &actNumber, actName, &actBalance);                        
        }

        fclose(fPtr);
    }
    return;
}

【问题讨论】:

  • while (!feof(stdin)) { 表示您需要按键盘上的 Ctrl-D 来终止标准输入流
  • 为了澄清 Netbeans 不是你的编译器,而是你的 IDE。 Netbeans 使用一些底层 C 编译器来构建您的代码。
  • @fukanchik 呃,我知道吗?它仍然是错误的。阅读链接的答案。

标签: c file loops input


【解决方案1】:

只有在您按下控制台上的特殊组合键时,才会在 stdin 上设置文件结束标记。

你可以使用scanf()的返回值让你的循环正常工作,像这样

while (scanf("%d%29s%lf", &actNumber, actName, &actBalance) == 3) 
{            
    fprintf(fPtr, "%d, %29s, %.2lf\n", actNumber, actName, actBalance);
    printf("%s", "?");
}

在输入流中留下第一个scanf() '\n' 字符后,当您在循环内再次调用scanf() 时,该字符被消耗然后被忽略,并且scanf() 无法返回小于的值大于 3,这个过程会不断重复,导致无限循环。

但是,以下解决方案更好。使用fgets() 可以更好地处理stdin 中未读的'\n' 字符,

char line[100];
while (fgets(line, sizeof(line), stdin) != NULL)
 {
    if (sscanf(line, "%d%29s%lf", &actNumber, actName, &actBalance) != 3)
        continue;
    fprintf(fPtr, "%d;%29s;%.2lf\n", actNumber, actName, actBalance);
    fprintf(stdout, "?");
 }

请注意,我删除了printf() 格式中的空格,并将, 替换为;,因为在某些语言环境中, 是小数分隔符,不使用它只是本能,你可以如果您确保. 是小数点分隔符,请使用它。

【讨论】:

  • 好吧,是的,通过标准循环条件工作感觉更直观。谢谢@iharob
猜你喜欢
  • 2015-07-17
  • 1970-01-01
  • 2012-09-28
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多