我想分析文本文件中的单词(每个单词的长度、起始字符等)。为此,第一步是从文件中读取每个单词,然后存储在一个数组中。
在下面的代码中,我设法将所有字符存储在一个数组中,但没有分离成单词。
#include <stdio.h>
#include <stdlib.h>
FILE *inp;
char arr[100];
int i = 0;
int word_count = 0;
char c;
int char_count = 0;
inp = fopen("string_in.txt", "r");
while ((c = fgetc(inp)) != EOF) {
if (c == ' ' || c == '\n') {
printf("\n");
arr[char_count] = c;
word_count++;
}
else {
//printf("%c", c); //print to check if file is being read correctly
arr[char_count] = c;
printf("%c",arr[char_count]);
}
char_count++;
}
printf("\n");
printf("Chars: %d, Words: %d\n", char_count, word_count+1);
printf("From array: \n");
for(i = 0; i <= word_count; i++) {
printf("%c",arr[word_count]);
}
printf("\n");
fclose(inp);
return (EXIT_SUCCESS);
输入文字:
This is a test
输出:
This
is
a
test
Chars: 15, Words: 4
From array:
This is a test
我想按如下方式访问元素:
arr[0] = 'This'
arr[3] = 'Test'
但是因为我是按字符而不是按单词的字符串:
arr[0] = 'T'
arr[3] = 's'
关于如何扩展它以存储完整单词有什么建议吗?
编辑:
根据下面的答案:
while ((c = fgetc(inp)) != EOF) {
if (c == ' ' || c == '\n') {
printf("\n");
arr[word_count][char_count] = '\0'; //Terminate the string
char_count = 0; //Reset the counter.
word_count++;
}
else {
arr[word_count][char_count] = c;
printf("%c",arr[word_count][char_count]);
}
(char_count < 99)? (char_count++):(char_count = 0);
}
printf("From array: \n");
for(i = 0; i < word_count; i++) {
printf("%s",arr[word_count]);
}
不打印数组的输出。
This
is
a
test
Chars: 5, Words: 4
From array:
Press [Enter] to close the terminal ...
最佳答案
目前您有空间来存储单个字符串
。
char arr[100]; -->char arr[100][100];
然后你的阅读变化如下。
while ((c = fgetc(inp)) != EOF) {
if (c == ' ' || c == '\n') {
printf("\n");
arr[word_count][char_count] = '\0'; //Terminate the string
char_count = 0; //Reset the counter.
word_count++;
}
else {
arr[word_count][char_count] = c;
printf("%c",arr[word_count][char_count]);
if (char_count < 99)
char_count++;
else
char_count = 0;
}
}
并且您的打印更改如下。
for(i = 0; i < word_count; i++) {
printf("%s",arr[i]);
}
关于c - 从文件到数组读取和存储整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591727/