add char to string c++ code example

Example 1: append string c++

// appending to string
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string str2="Writing ";
  std::string str3="print 10 and then 5 more";

  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10u,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."

  std::cout << str << '\n';
  return 0;
}

Example 2: integer to char c++

// for example you have such integer
int i = 3;

// and you want to convert it to a char so that
char c = '3';

what you need to do is, by adding i to '0'. The reason why it works is because '0' actually means an integer value of 48. '1'..'9' means 49..57. This is a simple addition to find out corresponding character for an single decimal digit integer:

i.e. char c = '0' + i;

If you know how to convert a single decimal digit int to char, whats left is how you can extract individual digit from a more-than-one-decimal-digit integer

it is simply a simple math by making use of / and %

int i = 123 % 10;  // give u last digit, which is 3
int j = 123 / 10;  // give remove the last digit, which is 12
The logic left is the homework you need to do then.

Example 3: c++ append a char to a string

// string::operator+=
#include <iostream>
#include <string>

int main ()
{
  std::string name ("John");
  std::string family ("Smith");
  name += " K. ";         // c-string
  name += family;         // string
  name += '\n';           // character

  std::cout << name;
  return 0;
}

Example 4: append string to another string c++

// appending to string
#include <iostream>
#include <string>

int main ()
{
  // easy way
  std::string str = "Hello";
  std::string str2 = " World";
  std::cout << str + str2 << std::endl;
  return 0;
}

Tags:

Cpp Example