所以我的程序应该做的是:用这段代码读取一个 .txt 文件。
FILE *fp;
char filename[40],part1[4],part2[4];
int c=0,pt1,pt2;
printf("\nEnter a file name to open: ");
gets(filename);
if ((fp = fopen(filename, "r"))!= NULL)
{
printf("\nThe file %s was opened successfully!",filename);
}
else
{
printf("\nThe file didnt open succesfully!");
}
然后像这样将每一行存储在 row
字符串中。
fgets(part1,4,fp);
pt1 = atoi(part1);
struct input
{
char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
};
struct input list[pt1];
while (c++ < pt1 )
{
fgets(list[c].row,30,fp);
printf ("\n%s", list[c].row);
}
但问题是,在那之后我必须把行字符串切成碎片(对于 exp,txt 的第一行是 <1 Glass 2 0 9 3 1>,其中每个数字代表一些东西)所以我想要的是将“1”放入代码 [3] 字符串中,将“Glass”放入名称 [30] 字符串等中。我尝试使用 isspace()
扫描行字符串以及每当它找到了一个空间,它将使用 strncpy()
从 0-(空间 - 1)复制行数组。出于某种原因,每当我运行程序时,程序都会停止工作。任何人都可以提出任何建议吗?
最佳答案
您似乎想分配一个大小为 pt1 的数组,但这行不通,因为这是编译时间,而 pt1 的值是未知的。
与:
struct input
{
char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
};
你声明了一个变量,但你似乎想定义一个类型,所以:
typedef struct input
{
char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
};
然后你必须 malloc 内存:
struct input list= calloc(pt1, sizeof(struct input));
声明
struct input list[pt1];
应该给出一个编译器错误(用我的编译器)。
关于c - 我如何在 C 中将数组的某些部分复制到另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343215/