[英]How to store each word of a txt file into a 2d array
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 == '\0')
{
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;
}
My goal here is whever I find a word to store it in a 2d array but here I am comaring characters through the ch = fgetc(in_file) command.我的目标是无论何时找到一个单词将其存储在二维数组中,但在这里我通过 ch = fgetc(in_file) 命令比较字符。 I need to somehow form a word and store it in an array.
我需要以某种方式形成一个词并将其存储在一个数组中。 Any help would be useful.
任何帮助都会很有用。
Hello Manolis lordanidis,你好 Manolis lordanidis,
Here is the core code:下面是核心代码:
// 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 == '\0') {
words++;
// One word end. Now we need to put the word into str array.
word[word_len++] = '\0';
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++] = '\0';
printf("Get: %s.\n", word);
str[str_len++] = malloc((word_len) * sizeof(char));
memcpy(str[str_len - 1], word, (word_len) * sizeof(char));
In my opinion, the 2D array may be a array of word, which type is char*
, right?在我看来,二维数组可能是一个单词数组,类型是
char*
,对吧? You can use a really 2D array.您可以使用真正的二维数组。 Do not worry.
不要担心。
In here I am using malloc
function to ask for a array at runtime.在这里,我使用
malloc
function 在运行时请求一个数组。
Every time, if the character is not space or something same, it will push the character to the array word
.每次,如果字符不是空格或相同的东西,它会将字符推入数组
word
。 Then when it meet the space or something same or end-of-line (EOF), it will push the word to the str
array.然后当它遇到空格或相同的东西或行尾 (EOF) 时,它会将单词推入
str
数组。
I really hope it is helpful for you.我真的希望它对你有帮助。
If you like using malloc
, do not forget call function free
:)如果您喜欢使用
malloc
,请不要忘记free
拨打 function :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.