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

C++读取文件数字字符串后无法按原格式输出的问题

解决C++读取文件后还原原格式输出的问题

你的问题出在读取方式上:operator>>会自动跳过所有空白字符(空格、换行、制表符等),所以不管原文件里的数字是同行还是换行,都会被拆成单个的字符串读取,再加上cout << endl,自然每个数字单独占一行。

要还原原文件的行结构,有两种直接的解决方案:

方案1:直接按行读取并输出

如果不需要修改每行的内容,直接读取整行后输出即可,完全保留原格式:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    const string OSOBNIKI{ "start.txt" };
    ifstream file(OSOBNIKI);
    if (file)
    {
        string line;
        // 循环读取每一行,直到文件结束
        while (getline(file, line))
        {
            cout << line << endl;
        }
    }
    return 0;
}

方案2:读取每行后处理数字再输出

如果需要对每行的数字做额外处理(比如转换类型、验证格式),可以先读整行,再用istringstream拆分每行的数字,处理后按空格拼接输出:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    const string OSOBNIKI{ "start.txt" };
    ifstream file(OSOBNIKI);
    if (file)
    {
        string line;
        while (getline(file, line))
        {
            istringstream line_stream(line);
            string num;
            bool is_first_num = true;
            
            // 拆分当前行的每个数字
            while (line_stream >> num)
            {
                // 这里可以添加对num的处理逻辑,比如转成int、校验格式等
                if (!is_first_num)
                {
                    cout << " "; // 非第一个数字前加空格
                }
                cout << num;
                is_first_num = false;
            }
            cout << endl; // 每行结束后换行
        }
    }
    return 0;
}

两种方案都能实现你要的“按原文件格式,每行空格分隔输出数字”的效果,根据是否需要处理数字来选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:25:32