0

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?

1
  • Possibly not this, but wouldn't printf expect a c string i.e. char*? Same with scanf. Also why use printf and scanf instead std::cout and std::cin? Commented Apr 30, 2022 at 9:18

2 Answers 2

2

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 *;
Sign up to request clarification or add additional context in comments.

5 Comments

I have a task, out string with help printf. Do you know how do it?
@user18999150 You shall not use objects of the type std::string with scanf or printf though there is a possibility to output an object of the type std::string using printf for example the following way printf( "%s\n", str.c_str() ); or printf( "%s\n", str.data() );
@Klaus nitpick than isn't the same as then.
@user18999150 I suspect that they mean an alias of the type char * as I wrote in my answer.:) Or they just refer to C strings using the word string.
@Klaus it's not a "stupid task" at all. It makes you familiar how to interact with legacy c-libraries you cannot change, and have to use these in your daily, bread and butter, payed real world production code.
0

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 *...

1 Comment

In such an answer I expect at minimum that such coding should be avoided! Use C or C++... If someone gives such a task... there must be a very good reason for this! Teaching bad style should not be one of them...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.