将 <null> printf 与字符串一起使用
got <null> using printf with string
当使用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++类。所以这不起作用,因为:
printf
是一个纯C函数,它只知道如何处理基元类型(int
、double
、char *
等)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()肯定不能工作!
相关文章:
- 有没有办法在C++将字符串与开关语句一起使用?
- 我如何将 OR 与 if 语句一起使用字符串
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 将 NULL 与 C 的字符* 字符串一起使用
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 编译器如何将链表中的地址字符串在一起?
- 将find_last_of与字符串C++一起使用
- 在 c++ 中将 find_first_of 与字符串一起使用,而不是一组预定义字符
- 如何将adjacent_find与字符串C++一起使用
- 可以将std::getline()与从std::string中移出的字符串一起使用吗
- 如何在不使用模板的情况下将variadic函数与字符串一起使用
- 将 dirent->d_name 与字符串一起使用失败
- 如何将开关与字符串一起使用
- 将两个字符串一起分配,获取访问读取冲突
- C++ - 将 sendto() 与基本字符串一起使用
- 如何在C++中将 atoi 函数与字符串一起使用
- 将 <null> printf 与字符串一起使用
- 除非我通过data()或C_str()运行cout,否则无法将它与C++字符串一起使用
- C++-将.at()方法与字符串一起使用时出现问题
- 如何将replace_if与字符串一起使用