【问题标题】:why puts() does not work with declared string?为什么 puts() 不适用于声明的字符串?
【发布时间】:2019-01-17 23:26:28
【问题描述】:
char s[] = "asqa0";
string p;

cin >> p;

puts(s);
puts(p);

在这里,最后一个 puts(p); 给了我一个错误。 putsconst char *p 一起使用,其中指向的字符无法更改但指针可以自行更改,那么为什么它与 char 数组一起使用?

【问题讨论】:

  • 您正在使用 puts,它是带有 C++ 标准字符串的 C 打印函数。您可以使用 std::cout 或 puts(p.c_str()) 来修复您的代码。

标签: c++ string output puts


【解决方案1】:

puts() 需要一个以 null 结尾的 const char * 指针作为输入。

puts(s) 有效,因为s 是一个char[] 数组,衰减char * 指针,然后可隐式转换为const char * 指针。

puts(p) 不起作用,因为 pstd::string,并且没有将 std::string 作为输入的 puts() 重载。您需要使用std::string::c_str() 方法来获得一个合适的const char * 指向字符串数据的指针:

puts(p.c_str());

但是,在 C++ 中使用 puts() 根本没有充分的理由。改用std::cout,它已经为const char *std::string 数据重载了operator<<

cout << s;
cout << p;

【讨论】:

    猜你喜欢
    • 2019-03-06
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多