使用C ++在一行上读取多种数据类型 [英] Reading multiple data types on one line using C++

查看:104
本文介绍了使用C ++在一行上读取多种数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从dat文件中提取一个由整数以及char和float值组成的日期.

I am attempting to pull from a dat file a date composed of ints as well as a char and a float value that are together.

Dat文件格式如下:

Dat file format looks like:

201205171200 M29.65
201207041900 F30.3

以此类推.

我正在努力分离这些值. 这是我到目前为止的内容:

I am struggling with separating these values. Here is what I have so far:

    #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;
    }

}

我需要将第一部分作为时间戳分隔为一个整数.字符"M"或"F"必须是其自己的字符,最后一位必须是浮点数.

I need to separate the first part as a time stamp as an int. The char 'M' or 'F' needs to be its own char, and the the last bit needs to be a float.

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

I have no idea how to pull them as their own variables.

推荐答案

声明三个变量,并通过链式提取从文件中读取它们

Declare three variables and read them from the file with a chained extraction

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");

You will have to use something large enough to store the numbers. You can use a long long if that's big enough but it may not be large enough. You could check for this with a static_assert(std::numeric_limits<long long>::max() <= SOME_MAX_EXPECTED_VALUE, "long longs are too small");

这篇关于使用C ++在一行上读取多种数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆