c# - 使用 printf 打印字符串值

标签 c# c++ arrays

在 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

Live working example

#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/

相关文章:

C++ 向下转换(使用 dynamic_cast )返回 NULL?

c++ - 在 if 语句中 && 的后半部分进行无效操作是否安全?

c++ - 匿名命名空间歧义

c - 这个程序中的段错误是什么

php - 使用 "in_array"(php) w/mysql_query 时数组不包含值

窗口形式的一个窗口的 C# 多个 GUI

c# - 从这个堆栈开始的地方获取方法名称

java - C# Windows 窗体无法访问 REST API

c# - 在 C# 中检查每分钟的时间

javascript - 从嵌套在进一步嵌套在数组中的对象中的数组中随机选择元素的逻辑