从txt文件导入一些数据时遇到问题。
.txt文件中的格式化文件数据为:
(int int double)例如(16 21 18.0)
我已经创建了一个从文件中获取数据的函数,它可以工作,但它只是给我第一行(即第一个读取对象),然后它返回0,没有错误。我想输入循环有问题,但我无法理解哪个问题。我应该导入存储在txt文件中的所有50个值(50行和1列)。 提前谢谢。
Header3.h
#pragma once
struct Reading
{
int day, hour;
double temperature;
char ch1, ch2;
Reading();
Reading(char c1, int d, int h, double t, char c2);
};
istream& operator>>(istream& is, Reading& r); // Setting helper input function
ostream& operator<<(ostream& os, const vector<Reading>& r); // Setting helper output function
void vec_import(vector<Reading>& v); // Read data from txt file
temp_stats.cpp(header3的源文件)
#include "stdafx.h"
#include "std_lib_facilities.h"
#include "Header3.h"
void vec_import(vector<Reading>& v)
{
string iname;
cout << "Type input filename: ";
cin >> iname;
ifstream ist{ iname };
if (!ist) error("Cannot read from filename ", iname);
while (true)
{
Reading r;
ist >> r;
if (!ist) break;
v.push_back(r);
}
}
Reading::Reading()
:ch1{ ' ' }, day{ 0 }, hour{ 0 }, temperature{ 0 }, ch2{ ' ' } {};
Reading::Reading(char c1, int d, int h, double t, char c2)
:ch1{ c1 }, day{ d }, hour{ h }, temperature{ t }, ch2{ c2 } {};
istream& operator>>(istream& is, Reading& r)
{
int d, h;
double t;
char c1;
char c2;
is >> c1;
switch (c1)
{
case '(':
break;
default:
break;
return is;
}
is >> d >> h >> t;
is >> c2;
switch (c2)
{
case ')':
break;
default:
break;
return is;
}
r = Reading(c1, d, h, t, c2);
return is;
}
ostream& operator<<(ostream& os, const vector<Reading>& r)
{
for (int i = 0; i < r.size(); ++i)
{
return os << r[i].ch1 << " " << r[i].day << " " << r[i].hour
<< " " << setprecision(1) << fixed << r[i].temperature
<< " " << r[i].ch2 << endl;
}
}
的main.cpp
// Temperature Reading 2.0.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "std_lib_facilities.h"
#include "Header3.h"
int main()
{
Reading r;
vector<Reading> v;
vec_import(v);
cout << v;
keep_window_open();
return 0;
}
Txt文件:
答案 0 :(得分:0)
您的问题是operator<<()
。您将立即从循环返回,因此它只打印一个值。修复:
ostream& operator<<(ostream& os, const vector<Reading>& r)
{
for (int i = 0; i < r.size(); ++i)
{
os << r[i].ch1 << " " << r[i].day << " " << r[i].hour
<< " " << setprecision(1) << fixed << r[i].temperature
<< " " << r[i].ch2 << endl;
}
return os;
}