Lab 1 - Creating HTML Table using C/C++

Problem Statement

Write a C/C++ program that does the following:

  • Prompts the user for number of rows and columns
  • Takes input for each cell
  • Generates an HTML file containing the table
  • Saves the file locally

Code Implementation (C++)

C++ Code

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main() {
    int rows, cols;
    cout << "Enter number of columns: ";
    cin >> cols;
    cout << "Enter number of rows: ";
    cin >> rows;
    cin.ignore();

    vector<string> headers(cols);
    cout << "\nEnter names for each column heading:\n";
    for (int i = 0; i < cols; ++i) {
        cout << "Header " << i + 1 << ": ";
        getline(cin, headers[i]);
    }

    vector<vector<string>> data(rows, vector<string>(cols));
    cout << "\nEnter data for each row:\n";
    for (int i = 0; i < rows; ++i) {
        cout << "Row " << i + 1 << ":\n";
        for (int j = 0; j < cols; ++j) {
            cout << headers[j] << ": ";
            getline(cin, data[i][j]);
        }
    }

    string filePath = "C:\\Users\\shahe\\OneDrive\\Desktop\\IAD-LABS\\Lab-1\\generated_table.html";
    ofstream htmlFile(filePath);
    if (!htmlFile.is_open()) {
        cerr << "Failed to create HTML file at: " << filePath << "\n";
        return 1;
    }

    htmlFile << "<!DOCTYPE html>\n<html>\n<head>\n<style>\n";
    htmlFile << "table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; }\n";
    htmlFile << "td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; }\n";
    htmlFile << "tr:nth-child(even) { background-color: #dddddd; }\n";
    htmlFile << "</style>\n</head>\n<body>\n";
    htmlFile << "<h2>HTML Table</h2>\n<table>\n<tr>\n";

    for (const string& h : headers) {
        htmlFile << "<th>" << h << "</th>";
    }
    htmlFile << "</tr>\n";

    for (const auto& row : data) {
        htmlFile << "<tr>";
        for (const auto& cell : row) {
            htmlFile << "<td>" << cell << "</td>";
        }
        htmlFile << "</tr>\n";
    }

    htmlFile << "</table>\n</body>\n</html>";
    htmlFile.close();

    return 0;
}
                

HTML Code

<!DOCTYPE html>
<html>
<head>
<style>
table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; }
td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; }
tr:nth-child(even) { background-color: #dddddd; }
</style>
</head>
<body>
<h2>HTML Table</h2>
<table>
<tr>
<th>Name</th><th>Contacts</th><th>Country</th></tr>
<tr><td>Shaheena</td><td>0344010473</td><td>Pakistan</td></tr>
<tr><td>Aqsa</td><td>03246858216</td><td>Pakistan</td></tr>
<tr><td>Hanana Asif</td><td>03090078601</td><td>China</td></tr>
</table>
</body>
</html>

                

Sample Outputs

Description of image

Demonstration

Click the button below to view the generated HTML output file:

View Demo Table
Web hosting by Somee.com