zoudick97 2015-11-25 23:34 采纳率: 100%
浏览 1200
已采纳

c++代码错误,求教(结构体,动态分配)

 #include<string>
#include<iostream>
//#include<stdlib.h>
using namespace std;
struct book
{
    int ID;
    char* title ;
    int status;
};

void getCmdNum(const char *cmd,char *cmd1, char *cmd2);

int bookCounter = 0;
book *Book;
book *tempBook;

int main()
{
    string cmd;


    char* cmd_1;
    char* cmd_2;
    char* cmd_3;
    do
    {
        cout << ">>";
        getline(cin, cmd);
        cmd_1 = strtok((char*)cmd.data(), " ");
        cmd_2 = strtok(NULL, " ");
        cmd_3 = strtok(NULL, " ");
        getCmdNum((const char*)cmd_1, cmd_2, cmd_3);
    } while (1);
}

void getCmdNum(const char* cmd,char* cmd1,char* cmd2)
{
    if (!strcmp(cmd,"addbook"))
    {
        tempBook = new book[bookCounter];
        for (int i = 0; i < bookCounter; i++)
        {
            tempBook[i] = Book[i];
        }
        Book = new book[bookCounter+1];
        for (int i = 0; i < bookCounter;i++)
        {
            Book[i] = tempBook[i];
        }

        long ID = atol(cmd1);
        Book[bookCounter].ID = ID;
        Book[bookCounter].title = cmd2;
        bookCounter++;
    }
    if (!strcmp(cmd, "listbook"))
    {
        for (int i = 0; i < bookCounter; i++)
        {
            cout << (i + 1) << ".  " << Book[i].ID << "     " << Book[i].title;
            if (Book[i].status != 1)
                cout << "     on shelf" << endl;
            else
                cout << "     borrowed" << endl;
        }
    }
}

在运行的时候先addbook 在listbook然后book[].title会重叠出错,不知道是为什么。
输入格式为

addbook book[].ID book[].title

  • 写回答

3条回答 默认 最新

  • 普通网友 2015-11-26 02:58
    关注

    cout << (i + 1) << ". " << Book[i].ID << " " << Book[i].title;

    还有你的这一行,若果进来,因为你的Book[i].title此时指向的是NULL,所以输出肯定蹦...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么