字符串数组表

时间:2015-11-02 07:13:12

标签: c++ arrays

#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字符串数组。 有一个插入函数可以将字符串插入到数组中的某个位置。 然后打印功能应打印一个表格,其中包含相应框内的单词。 输出应该是这样的:

| ____ |两个| ______ |

|一个| _____ | 3 |

我被赋予int main并且无法改变任何东西。

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

  

与'operator ='不匹配   “((HTMLTABLE *)此) - &GT; HTMLTABLE :: m_Table [((HTMLTABLE *)此) - &GT; HTMLTABLE :: Y]

我过去的尝试只打印了最后一个春天,并重复了表格中的每个方框。 我在做什么错误的数组?我的打印功能也不正确吗?

1 个答案:

答案 0 :(得分:0)

这一行:

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

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

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

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

    int get_x = x;
    int get_y = x;
    

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

  • printrow从0循环到y,将col从0循环到x(如果x和{{} { {1}}已初始化),但始终写入y而不是m_Table[y][x]

你的m_Table[row][col]方法错了......因为你从未初始化x和y。你的构造函数应该是:

print

你不应该在insert中修改它们:

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

数组在C ++中被索引为0。你的主要应该包含:

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

BTW,生成的HTML不正确:您没有关闭t.insert(1,0, "one"); t.insert(0,1, "two"); t.insert(1,2, "three"); 代码,不会打开<tr>代码,并以奇怪的方式嵌套<td>代码,但这将是另一个故事..

相关问题