【问题标题】:Get the multiples from a file and copy them on another从文件中获取倍数并将它们复制到另一个文件中
【发布时间】:2016-01-05 00:40:49
【问题描述】:

我的目的是获取文件multiples.txt 中存在的所有数字并写入所需整数的倍数(由用户输入)。

#include <stdio.h>
int main() {
    FILE *f, *fs;
    int value, multiple, n;

    f = fopen("multiples.txt", "r");

    if (f == NULL)
        printf("Error\n");

    fs = fopen("exit.txt", "w");

    if (fs == NULL)
        printf("Error\n");

    printf("Write a number\n");
    scanf("%d", &value);

    do {
        n = fscanf(f, "%d", multiple);

        if (multiple % value == 0) {
            fprintf(fs, "%d", multiple);
        }

    } while (n != EOF);

    fclose(f);
    fclose(fs);
}

我的程序崩溃了,我不知道它是从哪里来的。

【问题讨论】:

    标签: c file scanf


    【解决方案1】:

    我将假设原来的 标签实际上是正确的,并给出一个答案,即(我认为)更好地利用 C++ 的功能而不仅仅是 C。

    由于我们要复制满足特定标准的项目,我们可以使用std::copy_if 算法来处理大部分工作。我们还需要为要复制的项目指定“规则”。我们通常希望使用流而不是 C 风格的 FILE *s,尤其是因为后者不支持迭代器。

    考虑到这些想法,我们会编写如下代码:

    #include <iostream>
    #include <algorithm>
    #include <fstream>
    #include <iterator>
    
    int main() {
        std::ifstream in("multiples.txt");
        std::ofstream out("exit.txt");
    
        std::cout << "Enter a number: ";
        int n;
        std::cin >> n;
    
        std::istream_iterator<int> begin(in), end;
    
        std::copy_if(begin, end,
            std::ostream_iterator<int>(out),
            [n](int i) { return i % n == 0; });
    }
    

    如您所见,这消除了最初提示问题的错误的机会(以及您在错误处理文件结尾时遇到的错误)。

    如果您打算在 C 中完成这项工作,您通常希望将读取输入与测试输入是否成功获得一个读取到文件末尾的循环相结合,然后在正确的时间停止。在这种情况下,您使用fscanf 阅读,因此正确编写循环的一种相当简单的方法如下所示:

    while (1 == fscanf(f, "%d", &multiple))
        if (multiple % value == 0)
            fprintf(fs, "%d", multiple);
    

    fscanf 的返回值是成功转换的“项目”数。这里我们要求读取/转换一个整数,然后测试是否发生。

    一个小的补充(适用于两者):我编写了上面的代码以在一个方面与问题中的内容相匹配:它写出结果数字,它们之间没有任何分隔符。例如,如果您有一个包含2 4 5 8 的输入并且用户输入了2,它将产生248 的输出,因此在结果中您将无法分辨哪些数字来自哪些输入。在实际使用中,您几乎肯定想用某些东西(逗号、空格、换行符等)将它们分开

    【讨论】:

      【解决方案2】:

      如果你只启用警告(-Wall 初学者),编译器只会告诉你

      test.cpp:20:29: warning: format specifies type 'int *' but the argument has type 'int' [-Wformat]
              n = fscanf(f, "%d", multiple);
                             ~~   ^~~~~~~~
      

      你忘了取multiple的地址

      始终使用工具来发现错误

      查看文档可以解决许多其他问题(例如http://linux.die.net/man/3/scanf

      【讨论】:

        【解决方案3】:
        n=fscanf(f, "%d", multiple);
        

        我觉得这点有点问题

        n=fscanf(f, "%d", &multiple);
        

        添加“&”

        【讨论】:

        • 另外,fscanf 不会在文件末尾返回 EOF。它返回匹配元素的数量。
        • 我认为 fscanf 返回你得到的数量。我推荐你 while( fscanf(f, "%d", &multiple) == 1 ) { //你想要什么。 } :)
        • 或multiples.txt中有字符,需要使用fgets检查是否为数字。
        • 但为什么 ==1?这对我来说没有意义
        猜你喜欢
        • 2016-05-08
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        • 2014-03-06
        • 2020-04-24
        相关资源
        最近更新 更多