简体   繁体   English

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

[英]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 ;
}

I got this output : 我得到了这个输出: 在此处输入图片说明

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;
}

Output : 输出: 在此处输入图片说明

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.

相关问题 为什么我会收到“没有可行的矢量转换” <Country> &#39;到&#39;int&#39;”? - Why am I getting “No viable conversion from 'vector<Country>' to 'int'”? 为什么我得到“从const指针到指针的无效转换?” - Why am I getting "invalid conversion from const pointer to pointer? 为什么我从随机数中得到相同的答案? - Why am I getting the same answer from random numbers? 为什么我收到转换函数错误? - Why am I getting a conversion function error? 为什么我得到两个输出而不是一个? - Why am I getting two outputs in place of a single one? 为什么我收到错误:无法转换 &#39;std::string {aka std::basic_string<char> }&#39; 到 &#39;char*&#39; 赋值? - Why am I getting error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char*’ in assignment? 为什么我会因为这个 dp 问题而稍微偏离输出? - why am i getting slightly off outputs for this dp problem? 不知道为什么使用字符串或char时会得到不同的长度 - Not sure why I am getting different lengths when using a string or a char 为什么我在 char 数组的末尾得到 i? - why I am getting i at the end of char array? 为什么在其他错误中出现从“ int”到“ int *”错误的无效转换? - Why am I getting the Invalid conversion from 'int' to 'int*' error among other errors?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM