gpt4 book ai didi

c - 在 strtok() 文件中的字符串行之后将日期存储在结构中

转载 作者:行者123 更新时间:2023-11-30 21:03:48 24 4
gpt4 key购买 nike

我尝试在字符串行上使用 strtok() 并将其元素放入结构元素中但我无法编写正确的代码...请帮忙

this is the main

store book;
char line[80];
printf("Insert book as:'title','author','publisher','ISBN','date of publication',and'category'\n");
gets(line);
char *p;
char s[2]=",";
p=strtok(line,s);

the struct

typedef struct bookStore{
char title[80];
char author[80];
char ISBN[20];
char date[20];
int numOfCopy;
int currNumOfcopy;
char category[20];
}store;

最佳答案

结构

您打印以下内容:

printf("Insert book as:'title','author','publisher','ISBN','date of publication',and'category'\n");

但你的结构却没有提及发布者。

它还包含两个 80 个字符长的字段和 3 个 20 个字符长的字段,但您只为要解析的字符串分配 80 个字符的缓冲区。

获取

这是 C 语言中错误存在的函数之一。永远不应该使用它,因为它会让你的程序容易受到 stackoverflow 的攻击(安全问题,而不是这个网站;))。

这是填写行变量的正确方法。

  fgets(line,80,stdin);

strtok

您可以使用输入字符串调用它来获取第一个标记,就像您所做的那样,然后您需要使用 NULL 而不是输入字符串来调用它来获取下一个标记。当它返回 NULL 时,您就会知道字符串中不再有标记。

该函数使用静态变量保持内部状态,这是一个不好的做法。在大多数情况下应避免这种做法。

填充您的结构

您可以使用 strcpy 来处理字符串,您需要 #include<string.h>

  p=strtok(line,s);
length = strlen(p); /* length should be declared int where you declare your variables */
if (length > 79) {
printf("You entered title which is %d characters, but 79 were expected", length);
exit(1);
}
strcpy(book.title, p); /* It's safe, because we already checked the length of the string */
}

如果您需要填充数字,则必须使用 sscanf

  int number;
sscanf(p,"%d", book.numOfCopy);

关于c - 在 strtok() 文件中的字符串行之后将日期存储在结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20555471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com