如何在C中的.txt文件中创建每个单词的结构? [英] How to create struct of every word in .txt file in C?
问题描述
如果给出的简短的.txt文件包含以下内容,您将如何为文件中特定行中的每个单词创建一个结构,并确定它前面是否带有*
if given a short .txt file that contained the following content, how would you go about creating a struct for every word in a specific line in the file and determining if it had an * before it
样本文件:
a *b c
*d e f
我创建了以下结构:
typedef struct Unit
{
bool hasStar;
char variable[1];
} unit;
因此,我想为例如a,* b和c创建一个结构.我不确定如何执行此操作,因此,如何最好地解决此问题的任何帮助都将令人惊奇
So I would want to create a struct for a, *b, and c for example. I'm not sure how to do this, so any help on how best to approach this would be amazing
推荐答案
首先,您必须至少将 char变量[1]
更改为 char varibale [3]
例如,用于存储字符串"* a".
Firstly, you have to change char variable[1]
to char varibale[3]
at least for storing the string "*a" for example.
您可以使用 fgets
从文件中逐行获取,然后使用 strtok
从行中将空格分隔.
You can get line by line from the file using fgets
then using strtok
to separate the line by space character.
FILE *fp = fopen("intput.txt", "r");
if(!fp)
// handle error.
char line[256];
while(fgets(line, sizeof(line), fp) {
// using strtok to split each line
}
要使用 strtok
分割行并在单词的开头验证星形符号 *
:
For spliting the line using strtok
and verify the star symbol *
at the begin of word:
char * token = strtok(line, " ");
while (token != NULL) {
strcpy(units[i].variable, token);
if (token[0] == '*')
units[i].hasStar = true;
else
units[i].hasStar = false;
strtok(NULL, " ");
i++;
}
在 fgets
的 while
循环之前,您必须声明 units
的大小并首先初始化 i
,例如下面的代码,我将数组 units
的大小初始化为等于100:
Before while
loop of fgets
, you have to declare the size of units
and initialize i
first, for example the code below, i initialize the size of array units
that is eaqual to 100:
unit units[100];
int i = 0;
这篇关于如何在C中的.txt文件中创建每个单词的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!