编写一个 C++ 程序以将文本文件转换为 HTML 文件

write a c++program to convert a text file to html file

本文关键字:文件 文本 转换 HTML 程序 C++ 一个      更新时间:2023-10-16

我是 c++ 的初学者,在网上找到了这个问题和代码,试图让它不仅可以读取他给出的文件,还可以读取任何 txt 文件,但它显示了一些问题,我不知道如何解决

文本文件就像常规文本文件一样,而不是HTML格式的txt文件

#include <iostream>
#include <fstream>
#include <map>
using namespace std;
istream findParagraph(istream& is, string& word) 
{
cout << "<br>" << endl;
}
int main(int argc, char* argv[]) 
{
argv[1] = "The Republic, by Plato.txt";
ifstream infile(argv[1]);
char ch = 0;
ofstream out("title.html");
out << "<html>" << endl
<< "<head>" << endl
<< "<title>" << argv[1] << "</title>" << endl
<< "</head>" << endl
<< "<body>" << endl;
typedef map<string, unsigned> dictionary_type;
dictionary_type words;
string word;
while (findParagraph(infile, word))
++words[word];
out << "</body>" << endl << "</html>";
} //end main
1>C:UsersUsersourcerepostxt2htmltxt2htmltxt2html.cpp(15,40): error C2440:  '=': cannot convert from 'const char [27]' to 'char *'

您需要一个将文本文件转换为最小 html 文件的基本程序。可以将文本文件的文件名作为参数传递给程序。

如果可执行程序的名称为"转换",则可以使用"convert input.txt"调用程序

您在命令行中输入的第一个参数将显示在 argv[1] 中,第二个参数将显示在 argv[2] 中,依此类推。 argv[0] 包含程序本身的名称。

因此,请调整 argv 参数的处理。顺便说一下,您还可以将输出 html 文件的名称作为附加参数,将用户 argv[2] 作为输出文件名。然后 ARGC 将是 3。

打开所有文件并检查错误后,我们将首先将初始标头信息写入输出 html 文件。

然后我们使用std::getline()函数逐行读取源文件,直到完全读取。

对于我们读取的每一行,我们将纯文本输出到 html 文件中,并添加一个换行符">
"。

最后,我们写结束标签,仅此而已。

请参阅随附的骨架示例程序,您可以使用该程序进一步发展您的想法。

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
int main(int argc, char *argv[])
{
// Filename is parameter
// Check if program has been invoked with on parameter
if (argc == 2) {
// Parameter is filename. Try to open the input text file
std::ifstream textFile(argv[1]);
// File could be opened 
if (textFile) {
// Now open the output file. Becuase, if this cannot be opened then no need to do further steps
std::ofstream htmlFile("title.html");
if (htmlFile) {
// All files are open. Start to build the output
// Start writing the header
htmlFile << "<html>" << 'n' << "<head>" << 'n' <<"<title>" << argv[1] << "</title>" << 'n' << "</head>" << 
"<body>" << 'n';
// Write the body
// Frist read a complete line
std::string line{};
while (std::getline(textFile, line)) {
// Write the line and append a <br>
htmlFile << line << "<br>" << 'n';
}
// End of body
htmlFile << "</body>" << 'n' << "</html>" << 'n';
}
else {
// Error. HTML file could not be opend
std::cerr << "Could not open output HTML file 'title.html'n";
}
}
else {
// Error. input text file could not be opend
std::cerr << "Could not open input text file '" << argv[1] << "'n";
}
}
else {
// // Error, program has not been invoked correctly
std::cerr << "Nof Filename given. Invoke this program ("<< argv[0] << ") with 'file name' as parametern";
}
return 0;
}