我正在读取文件,特别是文本文件中的 BLS 数据。有些地铁名称很长,因此该城市的数据会延伸到下一行。 文件片段:
999 26380 Houma-Thibodaux, LA 42 42 0 0 0 0 94
288 26420 Houston-The Woodlands-Sugar Land,
TX 4424 3046 4 0 1374 34 100
170 26580 Huntington-Ashland, WV-KY-OH 7 1 0 6 0 0 85
我需要将状态后的整数保存到向量中,因此首先将它们放入字符串变量“total,one,...,per”中。为了简洁起见,我省略了放置它们的向量。 当前两个整数、城市、州和接下来的七个整数位于同一行时(就像侯马和亨廷顿的情况一样),我的程序运行良好。
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
ifstream BLS;
vector <string> cities = {"Houston-The Woodlands-Sugar Land"};
string city, state, total, one, two, three, five, struc, per, temp;
BLS.open("trial.txt");
if (BLS.is_open()) {
string line;
while(getline(BLS, line)) {
istringstream sin(line);
getline(sin, temp, ' ');
getline(sin, temp, ' ');
getline(sin, city, ',');
for (int i = 0; i < (int) cities.size(); i++) {
if (city == cities[i]) {
if (getline(sin, line) ) {
istringstream in(line);
in >> state >> total >> one >> two >> three >> five >> struc >> per;
}
else {
sin.ignore();
getline(sin, line);
istringstream in(line);
in >> state >> total >> one >> two >> three >> five >> struc >> per;
}
cout << " " << city << " " << state << " " << total << " " << five << endl;
}
}
}
}
}
与 Houston 一样,“if”语句中的 getline 为空,因此执行“else”。但我希望 sin.ignore() 和 getline(sin, line) 再次阅读以下行:
TX 4424 3046 4 0 1374 34 100
但它永远不会。 getline(sin, line) 似乎继续读取空行。
任何帮助将不胜感激。
getline
如果数据没有清晰地组织成行,则不要使用
std::getline
。
此解决方案假设
city
不包含逗号。
// StackOverflow_77548359_BLS_data_Answer.ixx
// https://stackoverflow.com/q/77548359/22193627
export module StackOverflow_77548359_BLS_data_Answer;
import std;
struct BLS_Data
{
int temp1;
int temp2;
std::string city;
std::string state;
int total;
int one;
int two;
int three;
int five;
int struc;
int per;
friend auto operator<< (std::ostream& ost, BLS_Data const& bls) -> std::ostream&
{
ost << bls.temp1
<< ' ' << bls.temp2
<< ' ' << bls.city << ", " << bls.state
<< ' ' << bls.total
<< ' ' << bls.one
<< ' ' << bls.two
<< ' ' << bls.three
<< ' ' << bls.five
<< ' ' << bls.struc
<< ' ' << bls.per
<< '\n';
return ost;
}
friend auto operator>> (std::istream& ist, BLS_Data& bls) -> std::istream&
{
ist >> bls.temp1
>> bls.temp2
>> std::ws;
std::getline(ist, bls.city, ',');
ist >> bls.state
>> bls.total
>> bls.one
>> bls.two
>> bls.three
>> bls.five
>> bls.struc
>> bls.per;
ist.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return ist;
}
};
export int main()
{
std::string bls_data{ "StackOverflow_77548359_BLS_data.txt" };
std::ifstream ist(bls_data);
if (ist.is_open())
{
BLS_Data d;
while (ist >> d)
std::cout << d;
ist.close();
}
}
// end file: StackOverflow_77548359_BLS_data_Answer.ixx