[英]Program crashes after perfoming strcpy() function
我需要为学校分配作业方面的一些帮助,包括在书名,作者和出版日期之后对一些书进行排序。 所有信息在txt文件中使用字符串之间的分隔符作为字符串给出。 问题是我无法正确读取数据,尝试执行strcpy()后程序崩溃。 你们能帮我这个忙,告诉我我做错了什么吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book
{
char author[100],title[100];
int year;
};
int main()
{
struct book b[25];
int i,n;
char intro[25][150],*p;
const char delim[2] = "#";
FILE *fp;
fp=fopen("text.txt", "r");
fscanf(fp,"%d",&n);
for(i=0;i<=n;i++)
{
fgets(intro[i], sizeof (intro[i]), fp);
p=strtok(intro[i], delim);
strcpy(b[i].title,p);
p=strtok(NULL, delim);
strcpy(b[i].author,p); /// The program works until it reaches this point - after performing this strcpy() it crashes
if(p!=NULL)
{
p=strtok(NULL,delim);
b[i].year=atoi(p);
}
}
return 0;
}
输入的示例可能是这样的:
5
Lord Of The Rings#JRR Tolkien#2003
Emotional Intelligence#Daniel Goleman#1977
Harry Potter#JK Rowling#1997
The Foundation#Isaac Asimov#1952
Dune#Frank Herbert#1965
问题出在最初的fscanf()
调用之后,文件中还有换行符。
这个
fscanf(fp,"%d",&n);
读取5
,随后的fgets()
仅读取\\n
。 所以这不是您想要的。 使用fgets()
读取n
,然后使用sscanf()
或strto*
将其转换为整数。 例如,您可以执行以下操作来代替fscanf()
调用:
char str[256];
fgets(str, sizeof str, fp);
sscanf(str, "%d", &n);
从文件中读取n
。
您还应该检查strtok()
返回NULL。 如果这样做,您将很容易发现问题。
另外,您需要从0
到n-1
。 因此, for
循环中的条件是错误的。 它应该是
for(i=0; i<n; i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.