我有一个包含大量数据集的大文件,尽管标记为“--”但仍有一些空白,但出于某种原因未记录数据。其余数据将以 double 形式存储在 vector 中,我的问题是如何获取丢失的数据并将这些丢失的数据存储为零?我的数据文件的片段;
0 29.1 ---
0 65.9 ---
2 56.5 ---
6 19.7 44.3
9 69.8 64.9
11 118.6 64.8
7 35.7 64.1
if (myfile.is_open())
{
int count = 0;
while ( myfile.good() )
{
getline (myfile,line);
/*if (line == "---")
{
sun(0.0);
}*/
if (count > 6)
{
std::istringstream buffer(line);
int month;
double rain, sun;
if (buffer >> month >> rain >> sun)
{
Weather objName = {month, rain, sun};
data_weather.push_back(objName);
}
}
count++;
}
myfile.close();
最佳答案
一次读取一行数据作为字符串。检查是否为“--”。如果是则相同的 0.0,如果不是则转换为 double 并保存 double 。
string line;
while (getline(file, line))
{
if (line == "--")
{
save(0.0);
}
else
{
istringstrleam buf(line);
double value;
if (buf >> value)
{
save(value);
}
else
{
error("could not convert value");
}
}
}
我正在使用 istringstream 进行从字符串到 double 的转换。
更新
根据问题中有关文件格式的新信息,以下内容应该有效(但它是未经测试的代码)。
string line;
while (getline(file, line))
{
if (count > 6)
{
int month;
double rain, sun;
std::string sun_as_string;
std::istringstream buffer(line);
if (buffer >> month >> rain >> sun_as_string)
{
if (sun_as_string == "--")
{
sun = 0.0;
}
else
{
std::istringstream buffer2(sun_as_string);
if (!(buffer2 >> sun))
{
// couldn't convert the sun value, so just set to zero
sun = 0.0;
}
}
Weather objName = {month, rain, sun};
data_weather.push_back(objName);
}
}
++count;
}
基本思路与之前相同,将太阳值作为字符串读取,如果不是“--”则仅将其转换为 double 值。
关于c++ - 如何允许文本文件中丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879252/