***一些编辑: 整型关键字[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/