'Why am I getting these symbols in console, using printf()? [duplicate]

I have question about output in console

string str;
    scanf("%s", str);
    printf("%s", str);

Why do I get strange symbols, which have trouble with encoding?



Solution 1:[1]

std::string is a class (user-defined type). On the other hand, the conversion specifier s is designed to input or output character arrays. So the code snippet has undefined behavior.

Instead you could use operators >> and << overloaded for the class std::string to input or output data from/to streams like

std::string str;
std::cin >> str;
std::cout << str << '\n';

If you want to use the functions scanf and printf then use character arrays as for example

char str[100];

scanf( "%99s", str );
printf( "%s\n", str );

If as you wrote in a comment

I have a task, out string with help printf.

then in this case you should check whether string is indeed the standard C++ type or an alias for the type char * introduced like for example

typedef char *string;

or like

using string = char *;

Solution 2:[2]

printf and scanf expect variables of type [const] char * with an "%s" format specifier.

In general, the other answer to use std::cin / std::cout instead is preferrable.

If you absolutely must use printf to output a std::string, use the c_str() method to get access to a const char * representing the same string as in the std::string; example:

string str;
std::cin >> str;
printf("%s", str.c_str());

Note the const in const char* c_str() - meaning you are not allowed to change the returned string. So, it cannot be used for scanf. There, you'd have to stick to a char *...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2