在 C# 中,我可以轻松枚举字符串数组。但是,为什么下面的代码在 C++ 中不起作用?
int main(int argc, char ** argv)
{
string hi[] = { "hi", "cool", "what" };
for (string s : hi)
{
printf("%s \n", s);
}
return 0;
}
此外,我尝试使用它,但它也不起作用:
printf(s);
奇怪的是,整数数组确实有效,但使用 %d
.是的,我有 #include <string>
.
@chris 提供的错误信息(由 Clang 编译器生成):
main.cpp:12:25: error: cannot pass non-trivial object of type 'string' (aka
'basic_string<char, char_traits<char>, allocator<char> >'
) to variadic function; expected type from format string was 'char *' [-Wnon-pod-varargs]printf("%s \n", s); ~~ ^
main.cpp:12:25: note: did you mean to call the c_str() method?
printf("%s \n", s); ^ .c_str()
最佳答案
使用 std::cout
代替 printf
。
问题是您将 std::string
传递给 printf
,而您实际上需要 const char*
。使用 std::string::c_str
解决了这个问题。但最好不要首先使用 printf
。
#include <iostream>
#include <string>
int main(int argc, char** argv)
{
std::string hi[] = { "hi", "cool", "what" };
for (const std::string& s : hi) {
std::cout << s << std::endl;
}
return 0;
}
关于c# - 使用 printf 打印字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29870635/