使用 cout 打印字符数组的全部内容

新手上路,请多包涵

我对 C++ 很陌生(只是 Java 中的一个摇摇欲坠的背景),我对如何打印出 char 数组的全部内容感到困惑。我相信我需要使用循环,并将循环基于数组的长度,但是我的编译尝试没有成功。这就是我现在所拥有的。在此先感谢您的帮助!

 #include <iostream>
#include <string>

using namespace std;

void namePrinting(char name[])
{
   int i = 0;
   cout << "Name: ";
   while(i <= name.length() )
   {
   cout << name[i];
   i++;
   }

}

int main()
{
   string fullName;
   cout << "Enter name: ";
   cin >> fullName;
   char nameArray[fullName.length()];
   namePrinting(nameArray);
}

原文由 Chandy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 720
1 个回答

这有点 来自 OP,但我用谷歌搜索了“c++ print std::array char”,这是最热门的,但这些答案都没有涵盖如何使用 std::array<char, > .您不能将 operator<< 直接应用于数组,您需要先访问其 .data() 指针:

 #include <string>
#include <iostream>
#include <array>

int main()
{
  // a direct initialization example. Remember, need string legnth+1 for
  // a NUL terminator
  std::array<char, 6> bar{"hello"};
  // print to std::out using operator<< and the .data() ptr access
  std::cout << bar.data() << std::endl;

  // extra example copying the contents of a string to an array.
  std::string foo("how are you?");
  // {} initializes it to 0, giving us guaranteed NUL termination
  std::array<char, 24> tar{};
  // copy string to array, std::min ensures we won't overrun
  foo.copy(tar.data(), std::min(foo.length(), tar.size()-1));
  std::cout << tar.data() << std::endl;

  return 0;
}

输出:

 hello
how are you?

示范

原文由 yano 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题