如何声明一个16元素的字符数组?

时间:2014-04-15 00:57:13

标签: c++ arrays

问题在于......

"声明具有全局范围的16元素字符数组。在fillArray()中用字母A到P填充它,在forwardArray()中向前输出数组,然后在backArray()中向后输出数组。"

编辑:我正在解决这个问题。但正如我说的那样。我正在试着拔掉我的头发。我明天会去寻求帮助,但忘了有像这样的网站可以进一步向你解释。

main()
fillArray()
fowardArray()
backArray() 

////////////////////////////

#include <iostream>
#include <iomanip>
#include <cstring>
#include <ctype.h>
using namespace std;

int main()
{
cout << setprecision(3)
 << setiosflags(ios::fixed)
 << setiosflags(ios::showpoint);

int I, length;
char name[80];

cout << "Enter your first name good sir/miss! ";
cin >> name;

cout << "\nHello " << name << "\n\n";
length=0;
I=0;
while(name[I] !='\0')
{
    length++;

    I++;
}


cout << "Using our inline strlen function:\n " << name << ", the number of characters in your name is ";
cout << length;

cout << "\n\nUsing the library strlen() function:\n " << name << ", the number of characters    in your name is ";
cout << strlen(name);

//PartB---------------------------------------------------------------------------

int alphalength=0;

I=0;

while(name[I]!='\0')
{   

name[I]>='A'&& name[I]<='Z'||name[I]>='a'&& name[I]<='z';

if(isalpha(name[I])!=0)
    alphalength++;

    I++;
}


cout << "\n\n\n\n" << name << " the number of alphabetic characters in your name is ";
cout << alphalength << "\n\n";






system ("pause");
return 0;
}

2 个答案:

答案 0 :(得分:2)

我希望你先试试这个。无论如何,我很乐意提供帮助。

注意数组的细微差别是前进和后退。前向案例索引从0到15.反之则从15到0。

在fillArray()中,代码利用了chars在内部存储为整数的事实,并且字母按顺序表示,因此'A'+ 1是'B'等。

#include <iostream>
using namespace std;

const int NUM_ELEMENTS = 16;

//Declare a 16 element character array with global scope.
char yourArray[NUM_ELEMENTS];

//Fill it with letters A to P in fillArray(), 
void fillArray()
{
    char iterChar = 'A';

    for (int i = 0; i < NUM_ELEMENTS; i++)
    {
        yourArray[i] = iterChar;
        iterChar++;
    }
}

//output the array forward in forwardArray(),
void forwardArray()
{
    cout << "Forward Array [";

    for (int i = 0; i < NUM_ELEMENTS; i++)
    {
        cout << yourArray[i];
    }

    cout <<"]" << endl;
}    

//and then output the array backwards in backArray()."
void backwardArray()
{
    cout << "Backward Array [";

    for (int i = NUM_ELEMENTS-1; i >= 0; i--)
    {
        cout << yourArray[i];
    }

    cout << "]" << endl;
}

int main()
{
    fillArray();
    forwardArray();
    backwardArray();
    return 0;
}

答案 1 :(得分:0)

据我所知,在全球范围内宣布事物被认为是不好的做法,因此应该避免,但如果你必须:

#include <iostream>

char array[16];

int main()
{
#Your code

return 0;
}

如果你使用它,那么字符数组&#34; array&#34;在全球范围内。 如果你想用A到P填充它,只需在main()中用一个初始化数组的while循环开始你的代码,然后创建你需要的其他函数。