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

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

本文介绍了使用COUT打印的字符数组的全部内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C ++(只是在Java中一个摇摇欲坠的背景)和我难倒关于如何打印出一个字符数组的全部内容。我相信我需要使用一个循环,并立足于数组的长度循环,但我尝试编译未成功的会议。这是我现在所拥有的。预先感谢您的帮助!

 的#include<&iostream的GT;
#包括LT&;串GT;使用命名空间std;无效namePrinting(字符名称[])
{
   INT I = 0;
   COUT<< 名称: ;
   而(ⅰ&下; = name.length())
   {
   COUT<<名称[我]
   我++;
   }}诠释的main()
{
   字符串全名;
   COUT<< 输入名字: ;
   CIN>>全名;
   焦炭nameArray [fullName.length()];
   namePrinting(nameArray);
}


解决方案

先从简单的东西:

 字符c_array [3];
c_array [0] ='A';
c_array [1] ='B';
c_array [2] ='c'的;对(INT I = 0;我3; ++ⅰ)
{
  COUT<< c_array [I];
}
COUT<< ENDL;

,直到你明白那么多完美,不要走的更远。现在请注意,如果你空终止该数组,您可以通过整个事情 COUT 运营商的LT;< 会知道何时停止:

 字符c_array [4];
c_array [0] ='A';
c_array [1] ='B';
c_array [2] ='c'的;
c_array [3] = 0;COUT<< c_array<< ENDL;

你不能做到这一点与大多数其他类型的数组。的现在发现,你可以在的char [] 这种方式分配,它会是空终止的:

 字符c_array [20] =ABC;
COUT<< c_array<< ENDL;

您甚至可以省略数组的大小,编译器会推断出它:

 字符c_array [] =ABC; //这是一个char [4];
COUT<< c_array<< ENDL;

有几个不同的方法来读取用户输入到一个数组,但它听起来好像你已经知道了,而这个答案越来越长。

I am quite new to C++ (just a shaky background in Java) and I'm stumped about how to print out the entire contents of a char array. I believe I need to use a loop, and base the loop on the length of the array, but my attempts to compile aren't meeting with success. This is what I have right now. Thanks in advance for your help!

#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);
}
解决方案

Start with something simple:

char c_array[3];
c_array[0] = 'a';
c_array[1] = 'b';
c_array[2] = 'c';

for(int i=0 ; i<3 ; ++i)
{
  cout << c_array[i];
}
cout << endl;

Do not go farther until you understand that much perfectly. Now notice that if you null-terminate the array, you can pass the whole thing to cout, and operator<< will know when to stop:

char c_array[4];
c_array[0] = 'a';
c_array[1] = 'b';
c_array[2] = 'c';
c_array[3] = 0;

cout << c_array << endl;

You cannot do that with arrays of most other types. Now notice that you can assign a char[] this way, and it will be null-terminated:

char c_array[20] = "abc";
cout << c_array << endl;

You can even omit the size of the array, and the compiler will infer it:

char c_array[] = "abc";    // this is a char[4];
cout << c_array << endl;

There are a couple of different ways to read user input into an array, but it sounds as if you know that already, and this answer is getting long.

这篇关于使用COUT打印的字符数组的全部内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:02