c++ - 使用 C++ 在一行中读取多种数据类型

标签 c++ file io fstream istream

我正试图从一个 dat 文件中提取一个由 int 以及一个 char 和一个 float 值组成的日期。

Dat 文件格式如下:

201205171200 M29.65
201207041900 F30.3

等等。

我正在努力分离这些值。 这是我目前所拥有的:

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

using namespace std; 

int main() {
    int inCount = 0; //This variable will be used to keep track of what record is being read.
    vector<int> dates;
    vector<float> temps;
    // Open and retrieve data from text.
    ifstream inFile; 
    inFile.open("biodata.dat");//Opening Biodata file to begin going through data
    if(inFile)
    {
        char tempType;
        while(!inFile.eof())
          {
            if (inFile.eof()) break;
            inFile >> dates[inCount];
            cout << dates[inCount];
            inFile >> tempType;
            inFile >> temps[inCount];
                        if(tempType == 'F'){
                    temps[inCount] = (temps[inCount] - static_cast<float>(32)) * (5.0/9.0);
                }
            inCount++;

          }
    } else {
        cout << "The file did not load";
        return 0;
    }

}

我需要将第一部分作为时间戳分隔为 int。字符“M”或“F”需要是它自己的字符,最后一位需要是 float 。

我不知道如何将它们作为自己的变量。

最佳答案

声明三个变量并使用链式提取从文件中读取它们

ifstream inFile("biodata.dat");

std::string date; // since your values are so large
char mf;
double d;

while (inFile >> date >> mf >> d) {
    // use the vars here
}

您将不得不使用足够大的东西来存储数字。您可以使用 long long如果它足够大,但它可能不够大。您可以使用 static_assert(std::numeric_limits<long long>::max() <= SOME_MAX_EXPECTED_VALUE, "long longs are too small"); 进行检查

关于c++ - 使用 C++ 在一行中读取多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21129480/

相关文章:

java - 结构化数据文件读取器类

haskell - getArgs 如何工作?

c++ - boost::任何比较值?

c - 如何从文件创建一个字符数组?

image - 如何在 Go 中发送带有图像和一些参数的 http post 请求?

c - 在C语言中读取文件时,文件是否需要与程序位于同一文件夹中?如果是这样,有什么方法可以读取另一个文件夹中的文件吗?

java - 如何在 Java 中获得主文件夹(或 appdata 文件夹,对于 Windows)的写入权限?

c++ - 使用 DirectX 11 API 读取 HLSL 语义和注释?

c++ - 这个 makefile 是如何生成目标文件的?

c++ - QML ListView 计数为零,只有一些行可见