我正试图从一个 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/