如何将txt文件中的每个单词存储到2d数组中


int calc_stats(void)
{
char in_name[80];
FILE* in_file;
int ch, character = 0, space = 0, words = 0;
char str[30];
int i;
printf("Enter file name:n");
scanf("%s", in_name);
in_file = fopen(in_name, "r");
if (in_file == NULL)
printf("Can't open %s for reading.n", in_name);
else
{
while ((ch = fgetc(in_file)) != EOF)
{
character++;
if (ch == ' ')
{
space++;
}
if (ch == ' ' || ch == 't' || ch == 'n' || ch == '')
{
words++;
strcat(str, " ");
}
else
{
strcat(str, ch);
}
}
fclose(in_file);
printf("nNumber of characters = %d", character);
printf("nNumber of characters without space = %d", character - space);
printf("nNumber of words = %d", words);
}
return 0;
}

我的目标是无论何时我找到一个单词来存储它在2d数组中,但这里我通过ch = fgetc(in_file)命令比较字符。我需要以某种方式生成一个单词并将其存储在数组中。任何帮助都是有用的。

Hello Manolis lordanidis

核心代码:

// This is the place to hold your word (and its length).
static char word[256];
static int word_len = 0;
while ((ch = fgetc(in_file)) != EOF) {
character++;
if (ch == ' ') {
space++;
}
if (ch == ' ' || ch == 't' || ch == 'n' || ch == '') {
words++;
// One word end. Now we need to put the word into str array.
word[word_len++] = '';
printf("Get: %s.n", word);
str[str_len++] = malloc((word_len) * sizeof(char));
memcpy(str[str_len - 1], word, (word_len) * sizeof(char));
word_len = 0;
} else {
// Hold your character into the word.
printf("Push: %d.n", ch);
word[word_len++] = (char)ch;
}
}
// Do not forget the last word.
word[word_len++] = '';
printf("Get: %s.n", word);
str[str_len++] = malloc((word_len) * sizeof(char));
memcpy(str[str_len - 1], word, (word_len) * sizeof(char));

我认为二维数组可能是一个word数组,它的类型是char*,对吗?你可以使用2D数组。别担心。

在这里,我使用malloc函数在运行时请求数组。

每次,如果字符不是空格或其他相同的东西,它将把字符推入数组word。然后,当它遇到空格或相同的东西或行尾(EOF)时,它将把单词推入str数组。

我真的希望这对你有帮助。


如果你喜欢使用malloc,不要忘记调用free:)

最新更新