Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does printf output characters instead of data?

Why does printf output characters instead of data?
Looking at the code, you can relatively understand what I want to do, but it is unclear why the output is like this

#include <vector>
#include <string>
#include <cstdio>

class Person
{
public:
    Person(const std::string& name, uint16_t old)
        : m_Name(name)
        , m_Old(old) 
    {
    }

public:
    std::string GetName() const { return m_Name; }
    uint16_t GetOld() const { return m_Old; }

private:
    std::string m_Name;
    uint16_t m_Old;
};

int main()
{
    std::vector<Person> person = { Person("Kyle", 26), Person("Max", 20), Person("Josiah", 31) };
    for (uint16_t i = 0; i < person.size(); ++i)
    {
        printf("Name: %s Old: %u\n", person[i].GetName(), person[i].GetOld());
    }
    return 0;
}


> // output
>     Name: Ь·╣ Old: 1701607755 
>     Name: Ь·╣ Old: 7889229 
>     Name: Ь·╣ Old: 1769172810

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using printf with "%s" requires a char*/char const* (or something that decays into a char*, like char[]).
std::string has a method: c_str() which returns a char const* that you can pass to printf.

Therefore your printf line should be:

printf("Name: %s Old: %hu\n", person[i].GetName().c_str(), person[i].GetOld());

Note: I also changed %u to %hu – see @RemyLebeau’s comment above.

Alternatively you can use the C++ std::cout to print the std::string as is:

#include <iostream>

std::cout << "Name: " << person[i].GetName() << " Old: " << person[i].GetOld() << std::endl;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading