伙计们。 我在用 C 语言读取文件并将其放入数组、将数组的每个部分分配给一个变量时遇到问题。
文件看起来像这样:
A0005:Burger:2.39:Extra Cheese
A0006:Soda:1.35:Coke
....
问题是,当字符串到达冒号时,我不太明白如何在 C 中拆分字符串。
到目前为止,我尝试制作一个结构,尝试使用 strtok 和 getchar,但到目前为止没有成功。
这是我到目前为止得到的
#include <stdio.h>
struct menuItems{
char itemCode[5];
char itemName[50];
float itemPrice;
char itemDetails[50];
};
int main(void){
FILE *menuFile;
char line[255];
char c;
struct menuItems allMenu = {"","",0.0,""};
if ((menuFile = fopen("addon.txt", "r")) == NULL){
puts("File could not be opened.");
}
else{
printf("%-6s%-16s%-11s%10s\n", "Code", "Name", "Price", "Details");
while( fgets(line, sizeof(line), menuFile) != NULL ){
c = getchar();
while(c !='\n' && c != EOF){
fscanf(menuFile, "%5s[^:]%10s[^:]%f[^:]%s[^:]", allMenu.itemCode, allMenu.itemName, &allMenu.itemPrice, allMenu.itemDetails);
}
}
}
}
最佳答案
对于每一行你都需要做这样的事情:
/* your code till fgets followed by following */
/* get the first token */
token = strtok(line, ":");
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token ); /* you would rather store these in array or whatever you want to do with it. */
token = strtok(NULL, ":");
}
以下代码为包含 100 个菜单项的数组分配内存,并将给定的文件条目读入其中。您实际上可以计算输入文件中的行数并分配尽可能多的条目(而不是硬编码 100):
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
struct menuItem
{
char itemCode[5];
char itemName[50];
float itemPrice;
char itemDetails[50];
};
int main()
{
char line[255];
FILE *menuFile = fopen("addon.txt", "r");
struct menuItem * items =
(struct menuItem *) malloc (100 * sizeof (struct menuItem));
struct menuItem * mem = items;
while( fgets(line, sizeof(line), menuFile) != NULL )
{
char *token = strtok(line, ":");
assert(token != NULL);
strcpy(items->itemCode, token);
token = strtok(NULL, ":");
assert(token != NULL);
strcpy(items->itemName, token);
token = strtok(NULL, ":");
assert(token != NULL);
items->itemPrice = atof(token);
token = strtok(NULL, ":");
assert(token != NULL);
strcpy(items->itemDetails, token);
items++;
}
free(mem);
fclose(menuFile);
}
关于c - 从文件中读入C中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902041/