【个人笔记】printf如何输出string

调试代码是发现print那行一直输出不确定的乱码,原因在于: printf只能输出C语言内置的数据,而string不是内置的,只是一个扩展的类,这样肯定是链接错误的。
printf_s("the num of Gangs is : %d\n", gang.size());
	map<string, int>::iterator it = gang.begin();
	for (; it != gang.end(); it++)
	{
		printf("%s %d\n", it->first, it->second);
		cout << it->first << " " << it->second << endl;
	}

现在将代码改为:

printf_s("the num of Gangs is : %d\n", gang.size());
	map<string, int>::iterator it = gang.begin();
	for (; it != gang.end(); it++)
	{
		printf("%s %d\n", (it->first).c_str(), it->second);
		cout << it->first << " " << it->second << endl;
	}

也就是在string类型后加上c_str(),然后就能够运行了。

当然也可以使用cout进行输出。

猜你喜欢

转载自blog.csdn.net/flysky_jay/article/details/79441516