在某个角色之后得到一个单词?

时间:2016-10-24 01:35:02

标签: c++

我正在努力让自己成为一个程序,它会接受一个字符串并在某个字符之后给我一个字。所以,例如:

String theString = "hello \t world"; // or "borld \t bello";

在标签之后,我只想要“世界”而不是“你好”。由于某种原因,这一直在让我崩溃。

size_t delimiter = theString.find_last_of('\t');
char *test;

if (theString.find("hello") != string::npos) {
     strcpy(test, theString.substr(delimiter + 1).c_str());
else if (theString.find("borld") != string::npos) {
     strcpy(test, theString.substr(delimiter + 1).c_str());
}

cout << test;

2 个答案:

答案 0 :(得分:0)

总是出现同样的错误,为什么在没有初始化的情况下写入测试?

char *test; // no memory allocated so using it will cause a segfault
char test[50]; // just for explaining we allocate 50 bytes for pointer test
// char* test = new char[50]; // the same above but here dynamic memory
// delete[] test; // free up memory because dynamic memory is not automatically freed

答案 1 :(得分:0)

来自strcpy手册:

char *strcpy(char *dest, const char *src);

  

strcpy()函数复制src指向的字符串,包括          终止空字节('\ 0'),指向dest。

指向的缓冲区

在您的代码中,您将test声明为char*的指针,但您永远不会对其进行初始化。

因此,

test是指向不确定值的指针。然后,您尝试将数据复制到该inderminate位置,从而导致崩溃。

您可以通过初始化test指向可以strcpy的内存来轻松解决此问题。一定要允许不要超出缓冲区写入。