c++ - 显示一个三维结构数组

标签 c++ arrays multidimensional-array data-structures struct

我正在尝试使用 3D 结构数组创建学校类(class)表。

struct SPS
{
string Class;
string Teacher;
int noStudents;
};

struct SPS array[3][4][5];

概念 View :

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

我希望能够在特定位置输入数组,例如 [1][2][2]

这是我当前的代码,但它按预期运行。

cout << "Class:" << endl;
cin >> array[1][2][2].Class;
cout << "Teacher:" << endl;
cin >> array[1][2][2].Teacher;
cout << "Number of students:" << endl;
cin >> array[1][2][2].noStudents;

我正在尝试打印数组,但它没有在输出中显示:

for (int a = 0; a<3; a++)
{
    for (int b = 0; b<4; b++)
    {
        for (int c= 0; c<5; c++)
        {
            printf("%d\t", array[a][b][c]);
        }
        cout << "\n";
    }
    cout << "\n";
}

如有任何帮助,我们将不胜感激。

最佳答案

你不能像那样只输出整个结构。 printf()不是魔法。编译器应该如何知道要使用什么格式?

只需使用 cout<<输出结构的每个成员:

for (int a = 0; a<3; a++)
{
    for (int b = 0; b<4; b++)
    {
        for (int c= 0; c<5; c++)
        {
            cout << array[a][b][c].Class << ' '
                 << array[a][b][c].Teacher << ' '
                 << array[a][b][c].noStudents << '\n';
        }
        cout << "\n";
    }
    cout << "\n";
}

关于c++ - 显示一个三维结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50081591/

相关文章:

c++ - 如何在两张图像中找到对应点?

c++ - Windows 7 下的 Visual Studio 2015 缺少 Api-ms-win-core-errorhandling-l1-1-1.dll

ios - 重复数字数组

C - 指向数组中索引号的指针

c++ - 为什么这个参数包不能接受函数指针?

c++ - shared_ptr 如何处理到纯虚拟基类的复制?

php - 获取一个数组的键,该键位于另一个数组内并包含值

c++ - 根据输入的动态二维数组

java - 我怎样才能得到一个方阵并将其放入另一个矩阵?

matlab - 如何使用 repmat 将 1d 向量 reshape 为 3d 矩阵?