Add a char to each iteration for c++

Asked

Viewed 1,740 times

1

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

have the word "char" and inside a go to each loop I want a letter "h" to be added after the "h" of the "char" and in case it would look like this
"char" bow 1 ---> "chhar"
"chhar" bow2 --> "chhhar"....
....

3 answers

1


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

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

Below is a very simple code that allows 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;
}

0

There are many possible solutions to the question.

For example, it is possible to add the fixed characters outside the loop and the repeatable character inside it as in the code below, the problem of the code is that it is not protected, so the number Daes 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';
  • Is that a correct vector? But there’s no way I can do this letter increment otherwise? is because in the exercise I am doing I am limited to using only what I have learned so far that are conditional deviations and repetition structures

  • I do not know if I understood well, in case the letter you inform it has to be added right after the letter it contains in the word? For example the word "test" and you inform the letter "s" the word would have to stay "tesste" that’s it?

  • n needs to be a specific letter, I say in case I want to put in a specific letter of the word, for example test, a repetition of letters "s".

0

I understand what you’re asking and I think the simplest way to illustrate this is as follows:

 int main(){

int num_lines = 0, counter = 0;

Cout << "Triangle generator" << Endl; Cout << "Type the number of lines: " << Endl; Cin >> in rows;

for (counter = 1; counter <= num_lines; counter++){

cout <<"*"<< endl; /*e a cada vez que a leitura do "for" for feita, a resposta adicionar um "*" ao lado do "*" anterior*/}}

Correct me if I’m wrong. If this is the case, I am also researching a solution, after all, my first contact with programming was with python and, as it is not a strongly typed language, you can multiply char prints (something that with C++ is not possible, apparently). Research and Gambiarra time, bora pro Google.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.