Problem with a string attribute of an object

Asked

Viewed 35 times

1

Hello!

I’m having a problem with a member of the string type of my object. When I do the object.word assignment = "some word", the program even compiles and runs, but when I print the content, it shows totally different symbols.

Here the main code:

#include "palavra.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    Palavra p1;
    Palavra p2;

    p1.palavra = "abc";
    p2.palavra = "Olani";

    printf("%s, %s\n", p1.palavra, p2.palavra);

    return(0);
}

Word.cpp:

#include "palavra.h"
#include <iostream>

//passar a arvore
Palavra Palavra::palavrasemelhante(const Palavra& p1, const Palavra& p2)
{
    //se for igual as duas primeiras letras entao sao semelhantes
    if(p1.palavra[0] == p2.palavra[0])
    {
        if(p1.palavra[1] == p2.palavra[1]){
            return (p2);
        }
    }       
    return (p1);
}

const string Palavra::getString()
{
    //retornar palavra para comparação de igual igual
    return (this->palavra);
}

//sobrecarga de operador == para comparar dois objetos da classe Palavra
bool Palavra::operator == (Palavra &p2)
{
    //palavra==p2.getstring ou desse jeitoif ( 0 == strcmp(palavra, p2.getString()))
    if (palavra == p2.getString())
        return (true);

    else
        return (false);

}

and Word. h:

#include <iostream>
#include <string>

using std::string;

class Palavra 
{
    private:
        //int tamanho;
        //string palavra;

    public:
        Palavra palavrasemelhante(const Palavra &p1, const Palavra &p2);
        bool operator==(Palavra &p2);
        const string getString();
        string palavra;
};

When compiling and executing no error is pointed out, but when I see the content is like this:

inserir a descrição da imagem aqui

Thanks for the help!

  • A class Palavra that encapsulates an attribute string palavra to make palavra.palavra seems rather strange at least. Why not simplify and use two strings normal ? This even avoided having to define the operator == that ended up complicating even more, and the same for the tamanho which already obtain directly from string with size(). In short, what is the purpose of all this abstraction/complication ?

1 answer

0


The question is what you’re using printf to show what a string in pure C, that is to say a char*, but you actually have a std::string and not a char*.

This problem is visible when compiling. See the warning I get concerning this line:

printf("%s, %s\n", p1.palavra, p2.palavra);

||=== Build: Debug in Testc++ (Compiler: GNU GCC Compiler) ===|

...main.cpp|60|Warning: format '%s' expects argument of type 'char*'...

...main.cpp|60|Warning: format '%s' expects argument of type 'char*'...

||=== Build finished: 0 error(s), 2 Warning(s) (0 minute(s), 1 Second(s)) ===|

I minimized the compiler messages only to what is relevant

Can solve by keeping the printf with %s but for that you need to access the chars array that is inside the std::string through the method c_str:

printf("%s, %s\n", p1.palavra.c_str(), p2.palavra.c_str());
//                             ^---                ^---

Watch it work on Ideone

A more in-line approach with C++ would be to use cout, because this one was designed to deal with std::string:

cout << p1.palavra << ", " << p2.palavra << endl;

See also this example in Ideone

As a final note, see what I commented on. You now have a class with several methods that literally holds only one string, and ends up replicating logic that already exists in the string. If you just need the word then simplify and use a string and create a normal function for the palavrasemelhante. This way it will not only be simpler but more natural.

  • Thank you very much! As I am very used to programming only with C, I forgot these details of c++. I will arrange the class according to your tips. thanks again!

Browser other questions tagged

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