【问题标题】:C : Counting Each Character And Word In a Texf File to Dynamic Array in CC:将文本文件中的每个字符和单词计数到C中的动态数组中
【发布时间】:2020-10-04 08:46:29
【问题描述】:

例如,我有一个包含“我今天过得很愉快!”的文本文件,我想计算该文件中的每个字符和单词。 在示例中“有 3 a, 1 m”等。

我是 C 的新手,知道如何打开文件,如何在文件中找到特定的字符或单词,但无法弄清楚。你能帮我吗?

【问题讨论】:

    标签: c arrays file dynamic


    【解决方案1】:

    您需要学习的第一件事是如何一次打开和处理一个字符的文件。您可以使用以下程序执行此操作:

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        // Must provide one argument, the file to process.
    
        if (argc != 2) {
            fprintf(stderr, "Usage: myprog <inputFileName>\n");
            return 1;
        }
    
        // Try to open the file.
    
        FILE *inFile = fopen(argv[1], "r");
        if (inFile == NULL) {
            fprintf(stderr, "Cannot open '%s'\n", argv[1]);
            return 1;
        }
    
        // Process file, character by character, until finished.
    
        int ch;
        while ((ch = fgetc(inFile)) != EOF) {
            putchar(ch);  // <accumulate>
        }
    
        // Close file and exit.
    
        fclose(inFile);
        // <output>
        return 0;
    }
    

    然后就是将putchar 调用更改为您需要做的任何事情(累积字符数)并在退出main 函数之前输出该信息。

    【讨论】:

    • 实际上尝试用 2 个 for 循环来实现它,但 fscanf 只得到第一个单词,所以不知道如何将所有内容作为字符串(已经搜索过)并用 strtok();.. 。其实找了很多,但还是找不到路……
    猜你喜欢
    • 2014-11-07
    • 2018-06-02
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2013-02-20
    相关资源
    最近更新 更多