将 <null> printf 与字符串一起使用

got <null> using printf with string

本文关键字:字符串 一起 gt lt null printf      更新时间:2023-10-16

当使用printf作为字符串时,我得到:

string key = "123";
printf("Value is %s n", key);

//输出为:值为<空>

但如果我这样做:

string key = "123";
printf("Value is: ");
printf(key.c_str());

然后我得到:

//输出为:值为123

那么我在上做错了什么

打印%s

提前谢谢。

std::string是一个C++类。所以这不起作用,因为:

  1. printf是一个纯C函数,它只知道如何处理基元类型(intdoublechar *等)
  2. printf是一个变差函数。将类类型传递给可变函数会导致未定义的行为1

如果要显示字符串,请使用std::cout:

std::cout << key << "n";

如果您只是必须使用printf,那么这应该有效:

printf("%sn", key.c_str());

c_str是返回C样式字符串(即const char *)的成员函数。请记住,它有一些限制;在调用c_str()和使用结果之间,不能修改或删除string对象

const char *p = key.c_str();
key = "something else";
printf("%sn", p);  // Undefined behaviour


1.或者可能是实现定义的,我不记得了。不管怎样,结局都不会好

令牌%s告诉printf期望一个空终止const char*,您将向其传递一个std::string

正确的方法是:

printf("Value is %s n", key.c_str());

C++的方法是使用CCD_ 17。

printf是C库函数,需要C"string"(char*)作为%s格式。您已经发现,您可以使用cppstring.c_str()来获取此信息。另请参阅此问题。

C风格应该是

printf("Value is %s n", key.c_str()); // printf does need a nullterminated char*

C++风格将是

cout << "Value is %s " << key << endl; // cout can use std::string directly

除其他答案外:printf是一个变元函数,传递不是POD的类类型的对象是未定义的行为,std::string是不是POD的类别类型。当然,未定义的行为意味着任何事情都可能发生,但这种行为很容易检测到,一个好的编译器至少会对错误发出警告。

cout<lt;string可以工作,因为string类重载了运算符"<<",所以printf()肯定不能工作!