How to assign a character to a string position?

Asked

Viewed 273 times

3

I’m having some difficulty assigning a character to a certain position of string. I researched a lot before asking here and found nothing. Criticism is always welcome.

This function is a part of a hangman’s game that I’m doing which, if you hit the letter, should assign a character to a certain position of the string.

Obs. palavraAux has the same number of characters as the palavra and is filled with several "-".

bool acertou(char letra, string palavra, string *palavraAux, int *acertos) {
    bool acerto = false;
    for (int i = 0; i < palavra.length(); i++) {
        if (letra == palavra[i]) {
            acerto = true;
            (*acertos)++;
            palavraAux[i].push_back(letra); //Essa parte aqui
        }
    }
    return acerto;
}

1 answer

4


I think that’s what you want (simple, right?). I didn’t want to change too much and I kept your logic (I think it can be improved). I changed the pointer to reference which is the most correct in C++.

#include <iostream>
using namespace std;

bool acertou(char letra, string palavra, string &palavraAux, int &acertos) {
    bool acerto = false;
    for (int i = 0; i < palavra.length(); i++) {
        if (letra == palavra[i]) {
            acerto = true;
            acertos++;
            palavraAux[i] = letra;
        }
    }
    return acerto;
}

int main() {
    string palavra = "--------";
    int acertos = 0;
    acertou('a', "testando", palavra, acertos);
    cout << palavra;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It worked here, thank you, it was much simpler than I thought, I complicated it

Browser other questions tagged

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