#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
cout << (i + 1) << ". " << Book[i].ID << " " << Book[i].title;
还有你的这一行,若果进来,因为你的Book[i].title此时指向的是NULL,所以输出肯定蹦...
#if 0
#include
#include
//#include
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 *p = NULL;
char* cmd_1;
char* cmd_2;
char* cmd_3;
do
{
cout << ">>";
getline(cin, cmd);
cmd_1 = strtok_s((char*)cmd.data(), " ", &p);
cmd_2 = strtok_s(NULL, " ", &p);
cmd_3 = strtok_s(NULL, " ", &p);
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];
}
//此处崩溃!!! 原因:cmd1为NULL,而atol内部实现是参数为空的话会抛出异常,那么此处崩溃是正常的。详见网页
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;
}
}
}
#endif
详见MSDN
没看完,当然你的title用的时候是必须分配空间的。不能直接赋值...