You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++98下无需分隔符直接按列写入两列文本文件的方法

实现无分隔符按列写入文件的方案

完全可以实现,不管是用C标准库的FILE、C++标准库的ofstream,还是结合Qt4的文件操作类都能做到。核心思路是固定每列的宽度,让第二列内容从指定的起始位置开始写入,无需分隔符就能形成规整的列结构。

用C标准库FILE实现

借助fprintf的格式化输出功能,指定列宽即可:

#include <cstdio>
#include <string>

// 从lineEdit获取两列文本
std::string col1 = ui->lineEdit1->text().toStdString();
std::string col2 = ui->lineEdit2->text().toStdString();

FILE* fp = fopen("sample.conf", "a"); // 追加模式,需覆盖则换"w"
if (fp) {
    // %-15s 表示左对齐占15字符,不足补空格;第二列直接接续输出
    fprintf(fp, "%-15s%s\n", col1.c_str(), col2.c_str());
    fclose(fp);
}

用C++标准库ofstream实现

利用setw和left操纵符控制列宽:

#include <fstream>
#include <iomanip>
#include <string>

std::string col1 = ui->lineEdit1->text().toStdString();
std::string col2 = ui->lineEdit2->text().toStdString();

std::ofstream ofs("sample.conf", std::ios::app);
if (ofs.is_open()) {
    ofs << std::left << std::setw(15) << col1 << col2 << std::endl;
    ofs.close();
}

用Qt4的文件类实现

Qt4的QTextStream支持格式化输出,更贴合Qt项目场景:

#include <QFile>
#include <QTextStream>
#include <QString>

QString col1 = ui->lineEdit1->text();
QString col2 = ui->lineEdit2->text();

QFile file("sample.conf");
if (file.open(QIODevice::Append | QIODevice::Text)) {
    QTextStream out(&file);
    // 设置第一列宽度15、左对齐,写完后重置宽度再输出第二列
    out << qSetFieldWidth(15) << Qt::left << col1 << qSetFieldWidth(0) << col2 << endl;
    file.close();
}

注意事项

  • 需根据实际内容长度调整列宽,避免第一列内容溢出挤占第二列位置。
  • 若需覆盖原有文件,将打开模式替换为"w"(C/C++标准库)或QIODevice::WriteOnly | QIODevice::Truncate(Qt)。

内容的提问来源于stack exchange,提问作者Getchezaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:15:32