【发布时间】:2021-07-21 22:53:39
【问题描述】:
我对 C++ 很陌生。我有我需要我的程序执行的构建块,即:读取由命令行输入的文本文件(例如./textToHtml.exe Alien.txt),并在必要时通过实现正确的 HTML 标签从文本文件创建一个 html 文件。
我已经提供了下面的代码,以及 html 文件结构。这是一个项目,我需要在每一段和每一行空行之后有换行符<br>。我已经提供了最后一个 HTML 结构,就像我想要的那样。
请注意,我确信我有一些不必要的行或冗余代码。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
std::ifstream txtFile(argv[1]);
std::string fn = argv[1];
std::string fileName = fn.substr(0, fn.size() - 4);
if (txtFile)
{
std::ofstream html(fileName + "1.txt");
if (html)
{
html << "<HTML>\n"
<< "<head>\n"
<< "<title>";
std::string line{};
if (std::getline(txtFile, line))
{
html << line << "</title>" << '\n';
}
html << "</head>\n"
<< "<body>\n";
while (std::getline(txtFile, line))
{
html << line << "<br>" << '\n';
}
html << "</body>" << '\n'
<< "</html>" << '\n';
}
}
return 0;
}
HTML 文件如下所示:
<HTML>
<head>
<title>Are These Aliens Martians?</title>
</head>
<body>
<br>
<br>
an adaptation<br>
<br>
The men from Earth stared at the aliens.<br>
The little green men had pointed heads and<br>
orange toes with one long curly hair on each toe.<br>
<br>
H. G. Wells' novel The War of the Worlds (1898)<br>
has had an extraordinary influence on science fiction. <br>
Wells' Martians are a technologically advanced species<br>
with an ancient civilization. They somewhat resemble<br>
cephalopods, with large, bulky brown bodies and<br>
sixteen snake-like tentacles, in two groups of eight,<br>
around a quivering V-shaped mouth; they move around in<br>
100 feet tall tripod fighting-machines they assemble<br>
upon landing, killing everything in their path.<br>
<br>
<br>
<br>
by your name<br>
<br>
</body>
</html>
我需要 HTML 文件的样子:
<HTML>
<head>
<title>Are These Aliens Martians?</title> //my output has <br> here
<br>
<br>
an adaptation<br>
<br>
The men from Earth stared at the aliens.
The little green men had pointed heads and
orange toes with one long curly hair on each toe.<br> //Just need a <br> at the end of each paragraph
<br>
H. G. Wells' novel The War of the Worlds (1898)
has had an extraordinary influence on science fiction.
Wells' Martians are a technologically advanced species
with an ancient civilization. They somewhat resemble
cephalopods, with large, bulky brown bodies and
sixteen snake-like tentacles, in two groups of eight,
around a quivering V-shaped mouth; they move around in
100 feet tall tripod fighting-machines they assemble
upon landing, killing everything in their path.<br> //Again just one <br> here not one each line
<br>
<br>
<br>
by your name<br>
<br>
</body>
</html>
【问题讨论】:
-
读完第一行后你永远不会关闭标题标签,你会直接跳入循环。
-
@AndreMotta 我需要写第一行,然后打印标题关闭标签,但不知道如何
-
仅供参考,您需要的不是有效的 HTML,因为没有
</head>标记,并且有一个没有<body>标记的</body>标记。 -
只写第一行,在循环前打印标题关闭标签:
if(std::getline(txtFile, line)) html << line << "</title>" << '\n'; -
使用
<p>和</p>标签怎么样?
标签: html c++ file ifstream writing