[英]Storing input file into multiple data types
我一直在研究如何将名称存储在包含空格字符的字符串中,然后将其余输入分别存储为int,char和double。 换句话说,有四个单独的数据类型:字符串,整数,字符,双精度型。
这是我需要逐行读取和提取数据的文件内容。 我需要提取名称才能适用于所有类型的名称。
此外,以下文件内容分别按此顺序排列:
字串:名称
整数:帐号
字符:帐户类型
双倍:用量
约翰·H·多伊1001 H 5693.3
詹姆斯·兰道夫(J.Randolph),小3333高1000.0
萨拉·劳伦斯·史密斯2456 H 3999999.5
好时光工业4678 C 10000000.1
大企业公司6757 I 12500849.9
妈妈和流行商店5002 C 4000000.7
O'Leary公司8022 I 9999999.9
到目前为止,这是我的一些代码:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage);
int main()
{
string billingDataFile = "Water Bill Records.txt";
string billingReportFile = "Water Bill Report.txt";
ifstream fin;
ofstream fout;
string name;
int accNum;
char type;
double usage;
fin.open(billingDataFile);
if (fin.fail())
{
cout << "\nError opening " << billingDataFile << " file for reading. \nProgram Terminated. \n";
system("pause");
return EXIT_FAILURE;
}
readBillingRecord(fin, name, accNum, type, usage);
system("pause");
return 0;
}
void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage)
{
fin >> name >> accNum >> type >> usage;
cout << name << accNum << type << usage << endl;
}
我讨厌成为“那个家伙”,但是,这确实让
但是,如果失败,并且假定没有任何尾随字段丢失(或“空”),那么提取这些字符串值的下一个最佳选择是(可悲):
对于文件中的每一行:
为了有效地做到这一点,您可能希望查看mmap()
和string_view
。
用流函数很难解析名称。 这是一个正则表达式解决方案:
void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage)
{
std::string line;
std::regex r{R"(([\D]*) (\d*) (\w) (\d*.?\d*))"};
std::smatch m;
while(getline(fin, line)){
std::regex_match(line, m, r);
name = m[1];
accNum = std::stoi(m[2]);
type = std::string{m[3]}[0];
usage = std::stod(m[4]);
std::cout << name << accNum << type << usage << endl;
}
}
还有一些错误检查:
void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage)
{
std::string line;
std::regex r{R"(([\D]*) (\d*) (\w) (\d*.?\d*))"};
std::smatch m;
while(getline(fin, line)){
static int line_count{-1};
++line_count;
if(!std::regex_match(line, m, r)) {
std::cout << "No match for line " << line_count << " with text: " << line << '\n';
continue;
}
name = m[1];
accNum = std::stoi(m[2]);
type = std::string{m[3]}[0];
usage = std::stod(m[4]);
std::cout << name << accNum << type << usage << endl;
}
}
对于以下输入:
John H. Doe 1001 H 5693.3
James Randolph, Jr. 3333 H 1000.0
Sara Law3rence-Smith 2456 H 3999999.5
Good Time Industries 4678 C 10000000.1
Big Business, Inc. 6757 I 12500849.9
Mom and Pop Shop 5002 C 4000000.7
The O'Leary Company 8022 I 9999999.9
生产:
John H. Doe 1001H5693.3
No match for line 1 with text:
James Randolph, Jr. 3333H1000
No match for line 3 with text: Sara Law3rence-Smith 2456 H 3999999.5
Good Time Industries 4678C1e+07
Big Business, Inc. 6757I1.25008e+07
Mom and Pop Shop 5002C4e+06
The O'Leary Company 8022I1e+07
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.