我有一个从文本文件中提取某些数据并显示输出的代码,该代码功能齐全并提供正确的输出。现在我希望该输出自动保存在文本文件中。那我该怎么做呢? 有人可以帮忙吗?
我无法添加代码,因为每次“看起来您的帖子大部分都是代码;请添加更多详细信息”时,都会出现此错误。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <cctype>
// true if line begins with s, but ignoring spaces
bool is_match(const std::string& line, const std::string& s) {
size_t i = 0, j = 0;
for (;;) {
while (i < line.size() && isspace(line[i]))
++i;
if (i >= line.size())
break;
while (j < s.size() && isspace(s[j]))
++j;
if (j >= s.size())
break;
if (line[i++] != s[j++])
return false;
}
return j == s.size();
}
int main() {
std::vector<std::string> titles {
"Subscriber number",
"Termination ID",
"Equipment ID",
"AGCU module number",
"Master/Slave type"
};
std::ifstream fin("LST_IMSBR.txt");
if (!fin) {
std::cerr << "Cannot open input file.\n";
return 1;
}
std::string line;
std::cout << "|Subscriber number"
"|Termination ID"
"| Equipment ID "
"|AGCU module number"
"|Master/Slave type|\n";
while (std::getline(fin, line)) {
std::vector<std::string> values(titles.size());
bool found = false;
while (std::getline(fin, line)) {
if (line.substr(0, 3) == "+++")
break;
for (size_t i = 0; i < titles.size(); ++i) {
if (is_match(line, titles[i])) {
size_t pos = line.find('=');
if (pos < line.size()) {
pos = line.find_first_not_of(" ", pos + 1);
if (pos < line.size()) {
found = true;
values[i] = line.substr(pos);
}
}
}
}
}
auto sw = std::setw;
if (found) {
std::cout << '|' << sw(11) << values[0] << " |";
std::cout << " " << sw( 4) << values[1] << " |";
std::cout << sw(16) << values[2] << "|";
std::cout << sw( 8) << values[3] << " |";
std::cout << " " << std::left << sw( 6) << values[4]
<< std::right << " |\n";
}
}
}
答案 0 :(得分:1)
您可以使用输出重定向到文件:
./a.out > ./a.log
答案 1 :(得分:1)
如果您的代码在控制台上可以正常工作,则可以更改最后一个if语句,我会考虑将for(;;)
更改为while(true)
。
删除:
std::cout << "|Subscriber number"
"|Termination ID"
"| Equipment ID "
"|AGCU module number"
"|Master/Slave type|\n";
编辑if语句。
if (found) {
std::ofstream ostrm("exaple.txt");
ostrm << "|Subscriber number"
"|Termination ID"
"| Equipment ID "
"|AGCU module number"
"|Master/Slave type|\n";
ostrm << '|' << sw(11) << values[0] << " |"
<< " " << sw(4) << values[1] << " |"
<< sw(16) << values[2] << "|"
<< sw(8) << values[3] << " |"
<< " " << std::left << sw(6) << values[4]
<< std::right << " |\n";
ostrm.close();
}