Append a char to each iteration for in c ++

1

How do I for each loop of a to add a char to a word, eg:

I have the word "char" and within a for each loop I want to add a letter "h" after the "h" of "char" and in case it would look like this "char" loop1 ---> "chhar"
"chhar" lace2 --- > "chhhar" ....
....

    
asked by anonymous 24.02.2016 / 13:50

2 answers

1

You put the question under the tag C ++, so a suggestion goes in c ++

Use the string class to make your life easier. You can use it with operators (sum and equality), as it is used in arithmetic (not all operators are defined, so be sure to always consult the documentation to be sure what you are doing).

Below is a very simple code that allows you to include 10 'h's in addition to the original, as in your suggestion in the question:

#include <string>
#include <iostream>

int main()
{
   std::string s;

   s = "ch";
   for (int i = 0; i < 10; ++i)
      s += 'h';
   s += "ar";
   std::cout << s << std::endl;
}
    
24.02.2016 / 21:30
0

There are many possible solutions to the question.

For example, you can add the fixed characters outside the loop and the repeatable character inside it as in the code below, the code problem is that it is not protected, so the number ofHs must be less than 252:

char meuChar[255];
meuChar[0] = 'c';
for( int i = 0; i < numeroDeHs; i++ )
{
    meuChar[i+1] = 'h';
}
meuChar[numeroDeHs] = 'a';
meuChar[numeroDeHs+1] = 'r';
    
24.02.2016 / 14:10