简体   繁体   English

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

[英]Program crashes after perfoming strcpy() function

I need some help with an assignement I have to do for school which consists in sorting some books after the title,author and the publication date of it. 我需要为学校分配作业方​​面的一些帮助,包括在书名,作者和出版日期之后对一些书进行排序。 All the infos are given as a string in a txt file using a delimiter between them. 所有信息在txt文件中使用字符串之间的分隔符作为字符串给出。 The problem is that I don't manage to properly read the data, my program crashes after I try to perform a strcpy(). 问题是我无法正确读取数据,尝试执行strcpy()后程序崩溃。 Can you guys help me with this and tell me what have I done wrong? 你们能帮我这个忙,告诉我我做错了什么吗?

#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;
}

An example of input could be this: 输入的示例可能是这样的:

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

The problem is with the newline left in the file after the initial fscanf() call. 问题出在最初的fscanf()调用之后,文件中还有换行符。

This 这个

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

reads the 5 and the subsequent fgets() reads just the \\n . 读取5 ,随后的fgets()仅读取\\n So this is not what you want. 所以这不是您想要的。 Read n using fgets() and convert it into integer using sscanf() or strto* . 使用fgets()读取n ,然后使用sscanf()strto*将其转换为整数。 For example, instead of the fscanf() call, you can do: 例如,您可以执行以下操作来代替fscanf()调用:

char str[256];

fgets(str, sizeof str, fp);
sscanf(str, "%d", &n);

to read the n from file. 从文件中读取n

You should also check if strtok() returns NULL. 您还应该检查strtok()返回NULL。 If you did, you would have figured out the issue easily. 如果这样做,您将很容易发现问题。

Also, your need to go from 0 to n-1 . 另外,您需要从0n-1 So the condition in the for loop is wrong. 因此, for循环中的条件是错误的。 It should be 它应该是

for(i=0; i<n; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM