c - 在 C 中执行文件操作时,数字被 append 而不是被添加到 int 变量中

标签 c file pointers append

我正在尝试将员工 ID 和他们完成的文件数量存储在文本文件中。还将文件数添加到totalFiles变量中。但是,当我输出 TotalFiles 的值时,我看到我提供的所有 append 输入都存储在文件内,而不是添加预期值。为什么会这样?

这是代码:

#include <stdio.h>

int main(void) {
    int n, i, numFiles;
    char empid[10];
    int totalfiles = 0;
    printf("Enter the number of employees\n");
    scanf("%d", &n);
    FILE *fp;
    fp = fopen("employee.txt", "w");
    if (fp == NULL) {
        printf("Error");
        return 0;
    }
    for (i = 0; i < n; i++) {
        printf("For employee %d\n", i + 1);
        printf("Enter the employee id\n");
        scanf("%s", empid);
        fputs(empid, fp);
        printf("Enter the number of files done\n");
        scanf("%d", &numFiles);
        totalfiles += numFiles;
        fprintf(fp, "%d", numFiles);
    }
    fclose(fp);
    printf("Total number of files done by all employees : %d", totalfiles);
}

我得到的输出是这样的:

Enter the number of employees
2
For employee 1
Enter the employee id
33
Enter the number of files done
8
For employee 2
Enter the employee id
20
Enter the number of files done
6
Total number of files done by all employees : 14338206

如果您看到输出,您会注意到输出什么也没有,只是我提供的输入只是彼此相邻 append 。请让我知道我的代码中的错误。提前致谢!

最佳答案

您的最终 printf 语句没有换行符,其输出不会与进一步的输出分开。 14 确实显示为输出,但紧接着是一些其他输出,可能是 employee.txt 文件的内容,该文件可能作为命令文件的一部分输出。

更改代码以输出每条信息的换行符:

#include <stdio.h>

int main(void) {
    int n, i, numFiles;
    char empid[10];
    int totalfiles = 0;
    printf("Enter the number of employees\n");
    if (scanf("%d", &n) != 1)
        return 1;
    FILE *fp;
    fp = fopen("employee.txt", "w");
    if (fp == NULL) {
        printf("Error");
        return 0;
    }
    for (i = 0; i < n; i++) {
        printf("For employee %d\n", i + 1);
        printf("Enter the employee id\n");
        if (scanf("%s", empid) != 1)
            return 1;
        fprintf(fp, "%s\n", empid);
        printf("Enter the number of files done\n");
        if (scanf("%d", &numFiles) != 1)
            return 1;
        totalfiles += numFiles;
        fprintf(fp, "%d\n", numFiles);
    }
    fclose(fp);
    printf("Total number of files done by all employees : %d\n", totalfiles);
    return 0;
}

关于c - 在 C 中执行文件操作时,数字被 append 而不是被添加到 int 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45162601/

相关文章:

android - 文件的图像 URI

python - 这段代码中的 'wb' 是什么意思,使用 Python?

C# 将 PDF 文件上传到 Firebase 项目存储?

c++ - 如何实现共享缓冲区?

c - 为什么OpenBSD <sys/queue.h> 中的尾队列使用指向指针的指针?

c++ - 容器、智能指针和模板化继承类

c - 如何在 GTK+ 2 中将 GtkButton 引用到 GtkNotebook 的多个页面

c - 构建一个带有使用assert()选项的c项目

c - 为什么要在函数序言/结语中使用 ebp?

c - 如何在新的 MacBookPro 上以编程方式激活 nVidia 卡以进行 CUDA 编程?