[英]C++ and printf - strange character output
I'm a complete newb to C++, but not to Java, C#, JavaScript, VB. 我是C ++的新手,但不是Java,C#,JavaScript,VB的新手。 I'm working with a default C++ console app from Visual Studio 2010.
我正在使用Visual Studio 2010中的默认C ++控制台应用程序。
In trying to do a printf I get some strange characters. 在尝试执行printf时,我得到了一些奇怪的字符。 Not the same each time which tells me they may be looking at different memory location each time I run it.
每次都不同,这告诉我他们每次运行它都可能在寻找不同的内存位置。
Code: 码:
#include "stdafx.h"
#include <string>
using namespace std;
class Person
{
public:
string first_name;
};
int _tmain(int argc, _TCHAR* argv[])
{
char somechar;
Person p;
p.first_name = "Bruno";
printf("Hello %s", p.first_name);
scanf("%c",&somechar);
return 0;
}
The problem is that printf
/ scanf
are not typesafe. 问题是
printf
/ scanf
不是类型安全的。 You're supplying a std::string
object where printf
expects a const char*
. 您正在提供一个
std::string
对象,其中printf
需要const char*
。
One way to fix this is to write 解决此问题的一种方法是编写
printf("Hello %s", p.first_name.c_str());
However, since you're coding in C++, it's a good idea to use I/O streams in preference to printf
/ scanf
: 但是,由于您使用C ++进行编码,因此优先使用I / O流优先于
printf
/ scanf
:
std::cout << p.first_name << std::endl;
std::cin >> c;
Convert the string to a c-string. 将字符串转换为c字符串。
printf("Hello %s", p.first_name.c_str());
Also, since you're using C++, you should learn about cout as opposed to printf! 另外,由于您使用的是C ++,因此您应该了解cout而不是printf!
Use printf("Hello %s",p.first_name.c_str());
使用
printf("Hello %s",p.first_name.c_str());
! !
printf("Hello %s", p.first_name.c_str());
但是,如果使用的是c ++,为什么不使用iostream?
You cannot pass C++ std::string
objects into printf
. 您不能将C ++
std::string
对象传递给printf
。 printf
only understands the primitive types like int
, float
, and char*
. printf
仅了解基本类型,例如int
, float
和char*
。 Your compiler should be giving you a warning there; 您的编译器应该在那里警告您。 if it's not, crank up your warning level.
如果不是,请提高您的警告级别。
Since you're using C++, you really should be using std::cout
for text output, and that does understand std::string
objects. 由于您使用的是C ++,因此您确实应该使用
std::cout
进行文本输出,并且确实可以理解std::string
对象。 If you really have to use printf
for some reason, then convert the std::string
to a const char*
by calling the c_str()
method on it. 如果由于某种原因确实必须使用
printf
,则可以通过在其上调用c_str()
方法将std::string
转换为const char*
。
printf("%s")
accepts a c-style string which is terminated by a '\\0'
. printf("%s")
接受c样式的字符串,该字符串以'\\0'
结尾。 However, string
object is C++ object which is different from a c-style string. 但是,
string
对象是C ++对象,与c样式的字符串不同。 You should use std::cout
which is overloaded to handle string
type directly, as shown below. 您应该使用
std::cout
,它被重载以直接处理string
类型,如下所示。
std::cout << p.first_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.