程序在执行strcpy()函数后崩溃

时间:2015-12-06 00:09:14

标签: c crash strcpy

我需要一些帮助,我必须为学校做一个分配,其中包括在标题,作者和出版日期之后对一些书进行分类。所有信息都在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

1 个答案:

答案 0 :(得分:0)

问题在于在初始fscanf()调用后文件中还有换行符。

fscanf(fp,"%d",&n);

读取5,后续fgets()只读取\n。所以这不是你想要的。使用n阅读fgets()并使用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++)
相关问题