如何从此输入文件中取出第一列,获取其余列(逐列)

How do I take the first column out from this input file, get the rest of the column(column by column)

我有一个包含以下行的文件。我想取出日期列并处理其余三列。最后我想添加 26 和 124、0 和 65、584 和 599 的值。

我已经试过了

double x,y,z;
ifstream in;
in.open(xyz.txt)
infile >> x >> y >> Z;

我也试过 get 行,但它只得到了一行代码。如果有 100 行不同的行,我想获取并添加除日期列之外的所有单独的列。

07/15/19 26 0 584

07/15/19 124 65 599

使用上面的代码我得到指数形式的输出

老实说,我不完全理解你的输入文件的结构和你想要达到的目的。人们真的很想帮助你,因此我建议添加更多数据。

您还应该在发布之前编译您的程序。它会告诉你已经有一些语法错误。不编译我可以告诉你有

  • 打开函数后缺少分号
  • open 函数中双引号中没有字符串
  • 最后一个语句中的大写 Z

编译器会向您显示所有这些错误。而且,如果你想得到 SO 成员的帮助,你至少应该出示编译后的代码。 . .

如前所述。我不知道你到底想做什么。不管怎样,请看下面的例子:

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

int main()
{
    // Open the input file 
    std::ifstream file("yourFileName.txt");

    // We must check, if the file could be opened
    if (file) { 
        std::string oneLine{};

        // Read all lines from file
        while(std::getline(file, oneLine)) {

            // Copy line to a stringstream, so that we can extract the data fields
            std::istringstream issLine(oneLine);

            // Define Variables that will be read from the line
            double x{0.0}, y{0.0}, z{0.0};
            std::string date{};

            // Extract the requested data
            issLine >> date >> x >> y >> z;

            //
            // Do some work with that data
            //
        }
    }
    else {
        std::cerr << "Could not open Input file\n";
    }
    return 0;
}

所以首先我们定义一个ifstream类型的变量文件,并将文件名作为参数传递给它的构造函数。这会尝试打开文件。当变量超出范围时,文件将由析构函数自动关闭。

然后我们检查文件是否可以打开。这行得通,因为 ! ifstream 的运算符已超载。如果无法打开文件,则会显示一条错误消息。

接下来我们使用getline函数从文件中读取完整的一行。我们将在 while 循环中执行此操作,以便我们逐行读取,直到读取文件中的所有行。

现在有点棘手了。因为我们要提取数据,所以我们将读取的行复制到一个 istringstream 对象。我们可以从这样的对象中提取数据。

然后我们提取所有数据,你可以用它做任何你想做的事。

我在网上用过的所有功能,请大家自行查找了解。阅读 C++ 书籍。

希望对您有所帮助。