C++ problem record: The string generated by using cout to output vsnprintf() in VS is garbled.

1. Introduction to the problem

When using Visual Studio to develop a C++ project, use vsnprintf() to generate a formatted string. When using std::cout to output the string, garbled characters are generated, but the result output using printf() is normal. The following is relevant Code and results, if you have any advice, please leave a message.

2. Code and results

Code:

#include <iostream>
using namespace std;

char* format(const char* format, ...)
{
    
    
	char format_str[1024] = {
    
     0 };
	va_list aptr;
	va_start(aptr, format);
	int ret = vsnprintf(format_str, 1024, format, aptr);
	format_str[ret] = '\0';
	printf("%d\n", ret);
	va_end(aptr);
	return format_str;
}

int main(int argc, char** argv)
{
    
    
	cout << "你好!1, 2,后面是string:test" << endl;
	cout << format("你好!%d, %d,后面是string:%s", 1, 2, "test") << endl;
	cout << format("%d aa %d abc %s", 1, 2, "test") << endl;
	printf("%s\n", format("%d aa %d abc %s", 1, 2, "test"));
	printf("%s\n", format("你好!%d, %d,后面是string:%s", 1, 2, "test"));
	return 0;
}

result:
Insert image description here

X. Reference

  1. [C/C++] Variable parameters

Guess you like

Origin blog.csdn.net/ice_bear221/article/details/132098714