c++ - 使用 C++ Code::Blocks 将文本文件中的单独部分读入 vector

标签 c++ vector inputstream

为了完成我的硕士论文,我需要用 C++ 编写程序,但我根本不是程序员。这也是我的第一个 C++ 程序,我以前在学校用 Java 编程。 我的问题如下。 我有这些包含一些数据的文本文件,如下所示: 如果您看不到图片:

index   date    month   WaveState   WindState
0   2015-01-01 00:00:00 1   9.0 8.0
1   2015-01-01 04:00:00 1   9.0 7.0
2   2015-01-01 08:00:00 1   9.0 8.0
3   2015-01-01 12:00:00 1   9.0 9.0
4   2015-01-01 16:00:00 1   9.0 8.0
5   2015-01-01 20:00:00 1   9.0 7.0
6   2015-01-02 00:00:00 1   9.0 4.0
7   2015-01-02 04:00:00 1   9.0 2.0
8   2015-01-02 08:00:00 1   9.0 1.0
9   2015-01-02 12:00:00 1   9.0 3.0
10  2015-01-02 16:00:00 1   9.0 4.0

等等。

现在我只需要从这些文本文件中提取考虑到“windstate”和“wavestate”的数字。我想将这些写到一个 vector 中,这样我就可以在我的程序中进一步轻松地使用它们。

这是我到目前为止写的代码:

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

using namespace std;

vector <string> dataVector;

int main()
{

    string line;
    ifstream myfile("wm994.txt");

    if(myfile.is_open())
    {

        while (getline(myfile,line))
        {
            dataVector.push_back(line);
        }
        myfile.close();
    }
    else cout << "Woops, couldn't open file!" << endl;

    for (unsigned i = 0; i<dataVector.size(); i++)
    {
       cout << dataVector.at(i) << endl;
    }

    return 0;
}

当然我的结果看起来是这样的。如果你看不到图片,我会为你描述。我认为在 vector 的每个位置,文本文件的整行都保存为一个字符串。但是我怎样才能访问'winddata'和'wavedata'这两个独立的部分呢?我希望写一些东西,将文本文件的每个单独部分放在 vector 中的单独位置,这样我就知道要访问哪些位置,然后获取我的风数据或波数据编号。但我真的不知道该怎么做。我试过这样的事情:

while (myfile)
    {
        // read stuff from the file into a string and print it
        myfile>> dataVector;            
    }

但这当然行不通。我可以做这样的事情吗?只有我的单独文本片段之间的空白被跳过,并且这些片段位于 vector 中的新位置?

我真的希望有人能帮我解决这个问题。我感到完全迷失了。提前谢谢你。

最佳答案

您应该拆分从文件中获得的每一行,并访问您将返回的 vector 的第三个 (WaveState) 和第四个 (WindState) 元素。下面是一个关于如何拆分字符串的示例。

String Split

关于c++ - 使用 C++ Code::Blocks 将文本文件中的单独部分读入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29017535/

相关文章:

java - 读取/写入文件时出现异常

c++ - 使用异步方法与线程等待

c++ - Windows 10 上带有 mingw 的 CMake : Detecting CXX compiler ABI info - failed

c++ - 在 unordered_map 中插入一个元素会出错

python - 异常 : "Invalid norm order for vectors" - Python

python - 如何用 python 编写处理文本流的程序?

java - inputStream 编码问题(特殊字符 : ñ, á,...)

c++ - 存储 FIX 消息的最佳数据结构是什么?

C++11 时钟:g++ steady_clock::is_steady == false?

android - 如何在 Android 的 Imageview 上制作正弦波?