【发布时间】:2014-04-13 11:46:03
【问题描述】:
由于某种原因,我的程序在第一个 while 循环中搞砸了,但我真的不明白为什么。昨天我为标准输入使用标准重定向输入,我假设打开一个文件基本上是一样的。为什么现在不工作了?
这是我保存为“.csv”并正在打开的文本文件:
热狗,10、2、1.50
小圆面包, 10, 2, 0.50
汉堡, 100, 10, 2.00
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i = 0, j = 0;
char command[25], str[100];
int quantity[100], limit[100];
double cost[100];
char *item[100];
char *token, *ptr;
FILE *fp = fopen("inventory.csv", "rw");
if(fp == NULL)
{
perror ("Error opening file");
}
//testing to see if program gets until here, then tries to copy data from CSV to arrays
while(fgets(str, 100, fp) != NULL)
{
token = strtok (str,",");
ptr = strdup(token);
item[i] = ptr;
sscanf (token, "%s", item[i]);
token = strtok (NULL,",");
sscanf (token, "%d", &quantity[i]);
token = strtok (NULL,",");
sscanf (token, "%d", &limit[i]);
token = strtok (NULL,"\n");
sscanf (token, "%lf", &cost[i]);
i++;
}
printf("hey");
for(j=0;j<i;j++)
{
printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]);
}
strcpy(command, argv[1]);
if(strcmp(command,"list") == 0)
{
for(j=0;j<i;j++)
{
printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]);
}
}
else
{
printf("wtf hello");
}
return 0;
}
【问题讨论】:
-
您将 fgets 指向标准输入,而不是您刚刚打开的文件。
-
即使把'stdin'改成'fp'还是不行
-
item[i]指向str的一部分。 -
我该如何准确地存储在 item[i] 中?这也不起作用:
token = strtok (str,","); sscanf (token, "%s", item[i]); -
我在分配项目之前将令牌复制到另一个指针,现在它可以工作了