【问题标题】:reading .txt file's 2nd line and write to another .txt file - C++读取 .txt 文件的第二行并写入另一个 .txt 文件 - C++
【发布时间】:2016-06-18 09:33:39
【问题描述】:

我有 79 个.txt 这样的文件:

iRun iDate showerEnergy thetaRad phiRad totalShowers totalParticles ???? e+ e- μ+ μ-
4001 121125 5e+07 1.61401 0.00118607 1 9929166 6909475 1271116 1399686 151330 148624
-1 4001 121125 5e+07 1.61401 0.00118607 2 9929167 6909475 1271116 1399686 151330 148624

它只有 3 行,第一行是 iRun iDate,第二行以 4001 开头,第三行以 -1 开头。我只想阅读这些文本文件的第二行。如果我清楚地阅读它们,我还想将所有 79 个文本文件的第 2 行写在一个文本文件中。

【问题讨论】:

  • 您想使用哪种语言?到目前为止,您尝试过什么?
  • 我是这种阅读/写作作品的新手。我想使用 C++ 语言,想要一个简单的东西,只想读取所有 x79 文件的所有第二行,如果我能够读/写一个,我可以制作其他的。
  • 很抱歉我的回答是针对 C# 而不是 C++。我刚删了。
  • 尝试查看all these answers,了解如何在 C++ 中按行读取文件
  • getline(fin, line); getline(fin, line); fout << line << std::endl;

标签: c++ string function getline


【解决方案1】:

这对于<fstream> 来说非常简单。一个非常基本的程序如下所示:

#include <fstream>
#include <string>

int main() {
    std::ifstream infile("indata.txt"); // Open input file
    std::string lineData = "";

    getline(infile, lineData); // Get first line.
    getline(infile, lineData); // Get second line.

    std::ofstream outfile;
    outfile.open("outdata.txt", std::ios_base::app);
    outfile << lineData << std::endl; // Append lineData to outfile. Creates the file if necessary.
    return 0;
}

【讨论】:

  • 这很有效,非常感谢。但我也想问一个简单的问题。我怎样才能在他们的第一行添加数字,我的意思是当我写第一个文本时我想添加 1,第二个等添加 2。
  • 当然,我不能在另一个文本文件中写入超过 1 个 txt 文件的第二行。我真的不明白。我如何为 40 多个 txt 文件复制您的方法?所有第 2 行必须转到 1 个通用文本文件。我可以先添加,第二个不行。
  • 您需要使用for 循环。我会让你调查如何做到这一点。有很多资源可以帮助您理解它们。
【解决方案2】:

试着写点东西。

伪代码如下所示

open outfile
for each text file
{
   open file
   skip line
   read line
   write line to out file
   close file
}
close output file

所以你要做的第一件事就是弄清楚如何枚举文件。两种选择:

剩下的就是简单的c++文件io

如果这是一个实际问题(而不是类分配),我会使用 awk、perl、sed 等而不是编写代码

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多