0

simple c++ program that adds a char byte to a string. The resulting length is wrong in the output.

#include <iostream>
#include <string>

int main(){

   char x = 0x01;

   std::string test;
   test = x+"test";

   std::cout << "length: " << test.length() << std::endl;
   std::cout << "test: " << test << std::endl;
   return 0;
}

the output:

length: 3
test: est

I am prepending a type byte to the string because I am going to be sending this data through a socket and the other side has a factory that needs to know the type of object to create.

user249806
  • 299
  • 1
  • 3
  • 14

2 Answers2

4
1 + "test" = "est"  // 1 offset from test

So you are getting the correct answer.

+---+---+---+---+---+
| t | e | s | t | \0|
+---+---+---+---+---+
  +0  +1  +2  +3  +4

What you want is possibly:

std::string test;
test += x;
test += "test";
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

You are not concatenating a char with a std::string as you think you are. This is because "test" is actually a literal const char*, so you are just doing pointer arithmetic when you add x to it. You can replace

test = x + "test";

with

test = std::to_string(x) + "test";

Then your output will be

length: 5
test: 1test
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218