字符串数组表

table of strings array

本文关键字:数组 字符串      更新时间:2023-10-16
#include <iostream>
#include "HtmlTable.h"
using namespace std;

int main()
{
   cout << "Content-type: text/html" << endl << endl;
   HtmlTable t(2,3);

   t.insert(2,1, "one");
   t.insert(1,2, "two");
   t.insert(2,3, "three");
   t.print();
   return 0;
}

#ifndef HTMLTABLE_H
#define HTMLTABLE_H
#include <string>
#include <iostream>
using namespace std;
class HtmlTable
{
public:
    HtmlTable(int y, int x)
    {
    }

    void print()
    {
        cout << "<table>";
        for (row=0; row<y; row++)
        {
            cout << "<tr>";
            for (col=0; col<x; col++)
            {
                cout << "<table border='1'>";
                cout << m_Table[y][x];
            }
            cout << "</td>";
        }
        cout << "</table>";

    }
    void insert(int row, int col, string text)
    {
        y = row;
        x = col;
        z = text;
        m_Table[y][x] = {{z,z,z,z},{z,z,z,z},{z,z,z,z},{z,z,z,z}};
    }

protected:
private:
    string m_Table[100][100];
    int row;
    int col;
    string text;
    int x;
    int y;
    string z;
    int get_x = x;
    int get_y = x;
};


#endif // HTMLTABLE_H

我必须创建一个字符串的 2d 数组。有一个插入函数可以将字符串插入数组中的某个位置。然后打印函数应该打印一个表格,其中包含相应框中的单词。输出应该是这样的:


|____| 二 |__

____|

|

一|____| 三|

我被给了 int 主要,无法更改任何东西。

我目前的问题是空插入。 错误是:

与"运算符="不匹配 '((HtmlTable*(this(->HtmlTable::m_Table[((HtmlTable*(this(->HtmlTable::y]

我过去的尝试只打印了最后一个春天,并对表格中的每个盒子重复。我错误地执行了什么数组?我的打印功能也不正确吗?

这一行:

m_Table[y][x] = {{z,z,z,z},{z,z,z,z},{z,z,z,z},{z,z,z,z}};

是完全错误的。 m_Table是 2D 数组或字符串,因此m_Table[y][x]只是一个std::string。你应该写:m_Table[y][x] = z .

但是您的代码中还有许多其他问题:

  • 在构造函数中传递数组维度HtmlTable但忽略它们
  • z, row, col, text不存储状态时,将它们声明为成员变量:它们应该是成员函数的局部变量
  • 这两行

    int get_x = x;
    int get_y = x;
    

    声明未使用的成员变量并尝试初始化它们,这是不正确的。成员变量应该在构造函数中初始化(整型静态常量变量除外(

  • print从 0 到 y 进行循环row,从 0 到 x col循环(如果初始化xy是正确的(,但始终写入m_Table[y][x]而不是m_Table[row][col]

而且你的print方法错了...因为你从未初始化过 x 和 y。构造函数应为:

HtmlTable(int y, int x): x(x), y(y)
{
}

并且您不应该在插入中修改它们:

void insert(int row, int col, string text)
{
    m_Table[row][col] = text;
}

数组在 C++ 中索引为 0。您的主要内容应包含:

t.insert(1,0, "one");
t.insert(0,1, "two");
t.insert(1,2, "three");

顺便说一句,生成的 HTML 是不正确的:您不关闭<tr>标签,不打开<td>标签,并以奇怪的方式嵌套<table>标签,但这将是另一回事......