c - 如何将文件中的单词保存到数组中?

标签 c arrays file fgets fgetc

***一些编辑: 整型关键字[16];

FILE *secretMessage;
secretMessage = fopen("C://Users/anyah/Fall2019/ECE_114/GreatGatsby.txt", "r");

char c;
char temp[100];
char temp2;
int i = 0;
int j = 0;

以上是我的变量声明方式。 我使用 atoi() 因为我无法将单词保存到数组中

我需要搜索一个文本文件并找到字符“_”。下划线后面是需要放入数组中的单词。然后我需要按照在文本文件中找到的相反顺序打印单词数组。

我了解如何打开文件、创建数组和搜索字符 - 我无法弄清楚如何将找到的字符保存到字符串中,然后再保存到数组中。

while(1)
{
        c = fgetc(secretMessage);
        if (c == '_')
        {
             while(1)
             {
                temp2 = fgetc(secretMessage);

                if (temp2 == ' ')
                    break;
                else
                    { 
                    temp[j] = temp2;
                    j++; 
                    };
            }
            int words = atoi(temp);
            keywords[i] = words;
            i++;
        }

        if (c==EOF)
        break;
    }

编译时我没有错误或警告 - 这是我当前的输出:

0 4200137 0 16 0 4200393 -1 -1 0 4200160 0 9900960 0 50 0 1

最佳答案

你可以这样做:

char strings[100][100]; // array of 100 strings, each of them has no more than 99 meaningful characters
while () // outer loop by words
{
    while () // inner loop by characters. Don't forget to check EOF here too!
    {
        strings[i][j] = temp2;
        j++;
    }
    strings[i][j] = 0; // null-terminated string!
    i++;
}
while () // printing loop by words
{
    printf("%s", strings[i]);
}

关于c - 如何将文件中的单词保存到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58443137/

相关文章:

c - 在宏扩展期间跟踪 C 预处理器执行的工具?

PHP : echo Multidimensional Array

java - 如何重命名本地安装的服务器上的文件?

file - MATLAB:将多个变量保存到 "-v7.3"(HDF5) .mat 文件在使用 "-append"标志时似乎更快。怎么来的?

mysql - 这是将数组存储在数据库中的可接受情况吗?

c - 我遇到了一个非常奇怪的计时错误,有些东西在我认为应该执行之前就已经执行了

c - 在 AVR 中将结构体设置为数组

c - 从文件中读取和打印

c - 为什么 printf() 中的命令\r 不起作用?

javascript - 数组的动态数组