为什么我会从此字符串到char转换中获得随机输出?

时间:2019-07-05 09:33:19

标签: c++ string char

我只是想将字符串转换为char(更确切地说是char *),但无缘无故,如果我在codeBlocks或项目中运行代码,则会得到不同的输出。因此,在codeBlocks上,我运行以下命令:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable ;
}

我得到了以下输出:enter image description here

在我的项目中,我在事件处理程序中运行相同的行:

void RePROGUIUser::applyOptions(wxCommandEvent& event) {
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable;
}

输出:enter image description here

所以我必须在GUI上按一个按钮才能实现,但是它实际上不应更改任何内容(我对将wxWidget标记放在此处表示怀疑)。

有人知道吗?

1 个答案:

答案 0 :(得分:6)

您的代码中有undefined behavior,表示一切皆有可能。请注意,null terminator'\0',而不是'\n'。所以改变

writable[stlstring.size()] = '\n';

writable[stlstring.size()] = '\0';