这是我从文本文件中读取数据并将其存储到矢量中的程序,我很难编译它,任何建议都会很棒。 id喜欢在这个例子中调用年和月的所有数据。 我希望它简单的错过了。
#include <iostream>
#include <libscat.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
struct Weather
{
int year;
int month;
double tempmax;
double tempmin;
};
int main()
{
vector<Weather> data_weather;
string line;
std::ifstream myfile ("weatherdata.txt");
if (myfile.is_open())
{
while ( getline(myfile, line) )
{ int count = 0;
if (count > 8)
{
std::istringstream buffer(line);
int year, mm;
double tmax, tmin;
if (buffer >> year >> mm >> tmax >> tmin)
{
Weather objName = {year, mm, tmax, tmin};
data_weather.push_back(objName);
count++;
}
}
for (auto it = data_weather.begin(); it != data_weather.end(); it++){
std::cout << it->year << " " << it->month << std::endl;}
myfile.close();
}
else
{
cout << "unable to open file";
}
scat::pause("\nPress <ENTER> to end the program.");
return 0;
}
}
答案 0 :(得分:0)
这是一个带有解释的固定版本,因为还没有任何真正的答案。
#include <iostream>
#include <libscat.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
struct Weather
{
int year;
int month;
double tempmax;
double tempmin;
};
int main()
{
std::vector<Weather> data_weather;
std::string line;
std::ifstream myfile("weatherdata.txt");
if (myfile.is_open())
{
int count = 0; // you gotta put it in front of the while loop or you'll
// create a new variable and initialize it to 0 every time
// you enter the loop
while ( getline(myfile, line) )
{
// int count = 0; // placed it just before the loop
if ( count > 8)
{
std::istringstream buffer(line);
int year, mm;
double tmax, tmin;
if (buffer >> year >> mm >> tmax >> tmin)
{
Weather objName = {year, mm, tmax, tmin};
data_weather.push_back(objName);
// count++; // you're still inside the if (count > 8)
// you'd probably want to have it outsided the if statement
// instead.
}
}
++count; //the count from inside. it'll probably do what you wanted
//it to do here.
// you'll probably want to run the for loop AFTER the while loop
// when the data_weather vector got fully filled
}
// the for loop from inside the while now outside
for (auto it = data_weather.begin(); it != data_weather.end(); ++it)
{
std::cout << it->year << " " << it->month << std::endl;
myfile.close();
}
}
else
{
std::cout << "unable to open file";
}
scat::pause("\nPress <Enter> to end the program.");
return 0;
}