我想使用的strtok()到信息存儲到我的結構。我的代碼看起來像這樣strtok的重寫我的變量
char *tempType = NULL, name[100], fileString[100];
int *tempItems = NULL, *tempCost = NULL;
FILE *infile = NULL;
ItemType myVector;
infile = fopen ("grocery_list.txt", "r");
while (!feof (infile))
{
fscanf (infile, "%s", &fileString);
tempType = strtok (fileString, ":");
tempCost = (int *) strtok (NULL, ":");
tempItems = (int *) strtok (NULL,":");
myVector.type[num_items] = tempType;
myVector.cost[num_items] = tempCost;
myVector.items[num_items] = tempItems;
num_items++;
}
每次我運行它,在myVector.type所有的值變爲「櫻桃」,我不知道爲什麼。我的infile: 蘋果:5:1 牛奶:3:2 麪包:3:1 糖果:10:1 奶酪:5:6個 桔子:4:2個 櫻桃:3:2
這不會編譯。沒有稱爲'num_items'的變量。 –
對不起,上面的行有int num_items = 0;但我忘了複製它 – user3277932
改正此:'fscanf(infile,「%s」,&fileString);'作爲'fscanf(infile,「%s」,fileString);' –