String array printing error // C++

Asked

Viewed 53 times

0

I am making a force and in the printing of the drawn word, there is an error in which the words are printed with some numbers or letters not included in its scope.

const int quant_palavras = 3;
class Forca {

    private : 

    char deposito[quant_palavras][20] {
        "escova",
        "escada",
        "boneca"

        };


    int setSorteio()  {
      int num;
      srand(time(NULL));
      num = rand() % (quant_palavras -1);
      return num;
    }

    void getpalavra_sorteada(int num) {
      for (int i=0; i <= 20; i++) {
        cout << deposito[num][i];
      }
    }

    public :

    void setpalavra_sorteada() {
      int ind = setSorteio();
      getpalavra_sorteada(ind);
      cout << setSorteio();
    } 



};

int main() {

  Forca display;

  display.setpalavra_sorteada();

  return 0;
}

For example, if you print the word "ladder", you print as : escadab1 doll : boneca2 brush : brush 0

I think the number is the position of the word, but what would the random letter be? How can I print only the word?

Thanks for your help.

1 answer

1


This is because the strings need to be finished with character 0 but you are printing a char array in the getpalavra_sorteada. But since you are using C++ it is best to declare the strings as type string which is more suitable. Here is an example of your changed code to use string:

#include <iostream>
#include <string>

using namespace std;

const int quant_palavras = 3;
class Forca {

    private : 

    string deposito[quant_palavras] {
        "escova",
        "escada",
        "boneca"

        };


    int setSorteio()  {
      int num;
      srand(time(NULL));
      num = rand() % (quant_palavras -1);
      return num;
    }

    void getpalavra_sorteada(int num) {
        cout << deposito[num];
        cout << "\n";
    }

    public :

    void setpalavra_sorteada() {
      int ind = setSorteio();
      getpalavra_sorteada(ind);
      cout << setSorteio();
    } 



};

int main() {

  Forca display;

  display.setpalavra_sorteada();

  return 0;
}
  • worked well. Thank you!

Browser other questions tagged

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