【问题标题】:storing letters from text file into array将文本文件中的字母存储到数组中
【发布时间】:2016-10-01 19:25:42
【问题描述】:

我有点困惑如何遍历数组并将每个字母添加到数组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;
}

我用这个作为参考: 诠释 c;

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

【问题讨论】:

  • 您将toupperisalpha 应用于文件句柄!!
  • 提示:对于学习,最好从令人尴尬的简单任务开始。在您的代码中,您处理 2 个不同的方面:文件和数组。从仅涉及数组的任务开始。分而治之;)
  • 我应用了文件句柄,我做错了吗? c 不是单独读取文件中的每个字符吗?

标签: c


【解决方案1】:

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

一些通用的cmets: a) 不要返回 -1。如果您希望代码符合 ANSI C,则返回 EXIT_SUCCESS 或 EXIT_FAILURE,或者返回 POSIX 平台的正数。

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

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

这是您的程序的精简版本,用于说明我的 cmets:

#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

【讨论】:

  • 谢谢,但是 jw,你为什么使用 size_t(我读到的是 unsigned)而不是 int?我假设它只允许更多的正数,对吗?
  • *我按照你说的修改了程序,但是还是不行,是while循环来获取整个字符串吗?如果我这样做了,'fgets(notes, sizeof notes, f)' 并且没有使用 while 循环,这不会填充数组吗?
  • @Submersed24 :我使用 size_t 因为那是 strlen() 返回的内容。
猜你喜欢
  • 2023-03-15
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多