c - 将文本文件中的字母存储到数组中

标签 c

我有点困惑如何遍历数组并将每个字母添加到数组 notes[] 中。我不确定是什么增加了 while 循环来扫描每个字符。我试图传递每个字符以查看它是否是字母,然后将其大写。

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

int main(){
    FILE * files;
    char notes[1000];
    int charcounter = 0, wordcounter = 0, c;
    files = fopen("input.txt", "r");
    if(!files)
    {
        return EXIT_FAILURE;
    }
    if(files)
    {
        while(fgets(notes, sizeof notes, files) != NULL)
        {
            size_t i, n = strlen(notes);

            for (i = 0; i < n; i++) 
            {
                if(isalpha(notes[i]))
                {
                    int c = toupper(notes[i]);
                    putchar(c);
                    if(wordcounter == 50)
                    {
                        printf("\n");
                        wordcounter = 0;
                    }

                    if(charcounter == 5)
                    {
                        printf(" ");
                        charcounter = 0;
                    }
                    wordcounter++;
                    charcounter++;
                }

            }
        }
    }
    fclose(files);
    system("PAUSE");
    return 0;
}

我用这个作为引用: int c;

FILE *file;
file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF)
        putchar(c);
    fclose(file);
}

最佳答案

fgets() 将文件中的字符串读取到字符数组中。在代码中,您将一个字符串读入名为 notes 的数组中。您应该迭代该变量中的每个字符,该变量是一个 C 字符串。

一些一般性评论: a) 不要返回-1。如果您希望代码符合 ANSI C 标准,则返回 EXIT_SUCCESS 或 EXIT_FAILURE,或者对于 POSIX 平台返回正数。

b) 在调用 fgets() 时使用 sizeof,而不是对数组长度进行两次硬编码。

c) isalpha()、toupper() 和 putchar() 需要一个 int 作为参数。您的代码使用 char[1000] 数组作为参数。如果没有警告/错误,这应该不会编译。 (我尝试过,并收到警告,正如预期的那样)。始终在启用所有警告的情况下进行编译是一个好习惯,它可以避免小错误。如果您使用 gcc,选项 -Wall -Wextra -pedantic 可能很有用,至少在调试之前是这样。

这是您的程序的精简版本,以说明我的评论:

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

int main(void)
{
    FILE *f;
    char notes[1000];

    f = fopen("input.txt", "r");
    if (!f) {
        return 1;
    }
    while (fgets(notes, sizeof notes, f) != NULL) {
        size_t i, n = strlen(notes);
        for (i = 0; i < n; i++) {
            int c = toupper(notes[i]);
            putchar(c);
        }
    }

    fclose(f);
    return 0;
}

HTH

关于c - 将文本文件中的字母存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810634/

相关文章:

c - 在 NUMA 机器上使用 CUDA 进行多 GPU 编程

c - 在这里用 gcc 创建/使用共享库有什么问题?

C编程动态初始化二维数组

c - 如何从头开始编写交叉编译器?

c - 在 Linux 中读取和写入相同文件描述符的问题

c - 什么是二进制数据?

c - 如何在程序中区分指针地址

c - Makefile编译

c - 用于缩短 C 中结构成员引用的宏

c - 编写读取 CFG 并删除左递归的解析器的建议