[英]Why am I getting random outputs from this string to char conversion?
I'm just trying to do a string conversion to char (more precisely char*) but for no reason, I got different outputs if I run the code on codeBlocks or in my project. 我只是想将字符串转换为char(更准确地说是char *),但无缘无故,如果我在codeBlocks或项目中运行代码,则会得到不同的输出。 So on codeBlocks, I run this :
因此,在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 ;
}
And in my project, I run the same lines but in an event handler : 在我的项目中,我在事件处理程序中运行相同的行:
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;
}
So I have to push a button on my GUI for that to happen but it really shouldn't change anything (and I was skeptical about putting the wxWidget tag here). 因此,我必须在GUI上按一个按钮才能实现,但是它实际上不应更改任何内容(我对将wxWidget标记放在此处表示怀疑)。
Any idea someone ? 有人知道吗?
You code has undefined behavior , means anything is possible. 您的代码具有未定义的行为 ,意味着一切皆有可能。 Note that the null terminator is
'\\0'
but not '\\n'
. 请注意, 空终止符为
'\\0'
而不是'\\n'
。 So change 所以改变
writable[stlstring.size()] = '\n';
to 至
writable[stlstring.size()] = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.