C++ C++;字符串未打印

C++ C++;字符串未打印,c++,string,C++,String,我有下一个代码: void addContent ( const std::string& message ) { std::string newMessage; for ( int i = 0, remainder = textCapacity - currentText; i < remainder; i++ ) { newMessage[i] = message[i]; std::cout << newMessage; //h

我有下一个代码:

void addContent ( const std::string& message ) {
   std::string newMessage;

   for ( int i = 0, remainder = textCapacity - currentText; i < remainder; i++ ) {
      newMessage[i] = message[i];
      std::cout << newMessage; //here nothing is printed
   }
}
void addContent(const std::string和message){
std::字符串newMessage;
对于(int i=0,余数=text容量-currentText;istd::cout
newMessage
是一个空的
std::string
。对它执行
[i]
操作就是访问无效内存。该字符串总是空的,而您只是在向无效内存写入。这是一个灾难的配方,您(不)幸运的是它没有对您造成崩溃


我不确定
message[I]
是什么,但您可能想要
newMessage[I]
=
message[I]
。但您最好跳过临时
newMessage
变量,只打印
message[I]
本身。

newMessage
是一个空字符串,因此不会打印任何内容。而且,
std::cout
是缓冲区,因此为了刷新缓冲区,您应该调用
std::endl
std::flush

我宁愿对此进行更改:

newMessage[i] = message[i];
为此:

newMessage += message[i];
打印时:

std::cout << newMessage<<std::endl;

std::cout正如Cornstales所说,您有一个越界访问权限

更重要的是,代码对于任务来说太复杂了。不要使用手动循环将一个
std::string
部分复制到另一个。要将
消息的一部分复制到
newMessage
,请在
消息上使用
substr
并分配:

newMessage = message.substr(from_index, number_of_chars);
或者是基于迭代器的东西:

std::string newMessage(message.begin() + from_index, message.begin() + to_index);
后者效率更高,所以你想要

std::string newMessage(message.begin(), message.begin() + (textCapacity - currentText));

将该字符串用作
newMessage[i]
意味着它是一个字符串数组。将该行替换为
std::string newMessage[textCapacity]

Try
std::cout
newMessage的可能重复项是一个空字符串。要查看放入Try/catch块中的错误。@没有人:这不是重复项,因为它不是缓冲。这是内存访问无效和空字符串。“一切都很好”-不,不是。现在您正在写入无效内存,然后重新读取刚才写入的内容。可能它看起来会工作;可能会崩溃;可能会损坏一些不相关的内容,并导致可怕的难以解决的错误。