Why does printf output characters instead of data?

Advertisements

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 :

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;

Leave a ReplyCancel reply