【发布时间】:2014-01-15 05:03:33
【问题描述】:
我试图从一个 dat 文件中提取一个由整数以及一个字符和一个浮点值组成的日期。
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。 char 'M' 或 'F' 需要是自己的 char,最后一位需要是浮点数。
我不知道如何将它们作为自己的变量。
【问题讨论】:
-
您的行
vector<int> dates;需要为vector<long long> dates;以确保其足够大以容纳这些数字。 -
另外,您似乎没有在任何地方管理矢量的大小。您可以读入局部变量,然后使用
push_back()将值添加到您的向量中,这样就可以解决这个问题。
标签: c++ file io fstream istream