[英]How to parse in this file in c++ dealing with spaces and new lines?
Credit 1 2 150 12345678 10-10-2020 123
Cash 2 3 199 200 1
Check 1 3 100 111000614 124356499
Credit 2 1 50 987654321 10-10-2021 321
我正在尝试在 c++ 中读取此文件,但我无法找到正确的方法。 我需要将每个单独的数据点读入不同的向量。 例如,在称为交易类型的向量中,Credit cash check Credit 将是Credit cash check Credit
。
这是我现在拥有的代码,它给了我非常奇怪的结果
file.open(fileName);
string line;
string space;
while(getline(file,line,'\n')){
cout<<"Row: ";
while(getline(file,space,' ')){
cout<<space<<" ";
}
}
cout<<space<<" ";
return 0;```
空格和换行符在 C++ 中被归类为(空白)空格,参见std::isspace 。 std::istream& operator>>(std::istream&, T&)
跳过所有空格,因此不需要对空格或换行符进行特殊处理。
一个例子:
#include <iostream>
#include <string>
#include <vector>
struct Date {
unsigned yyyymmdd;
};
std::istream& operator>>(std::istream& s, Date& date) {
std::string t;
s >> t;
int dd = std::stoi(t.substr(0, 2));
int mm = std::stoi(t.substr(3, 2));
int yyyy = std::stoi(t.substr(6, 4));
date.yyyymmdd = yyyy * 10000 + mm * 100 + dd;
return s;
}
struct Credit {
int a, b, c, d, f;
Date e;
};
std::istream& operator>>(std::istream& s, Credit& c) {
return s >> c.a >> c.b >> c.c >> c.d >> c.e >> c.f;
}
struct Cash {
int a, b, c, d, e;
};
std::istream& operator>>(std::istream& s, Cash& c) {
return s >> c.a >> c.b >> c.c >> c.d >> c.e;
}
struct Check {
int a, b, c, d, e;
};
std::istream& operator>>(std::istream& s, Check& c) {
return s >> c.a >> c.b >> c.c >> c.d >> c.e;
}
template<class V>
void load_element(V& v, std::istream& s) {
v.emplace_back();
s >> v.back();
}
struct Data {
std::vector<Credit> credits;
std::vector<Cash> cashs;
std::vector<Check> checks;
Data(std::istream& s) {
for(std::string type; s >> type;) {
if(type == "Credit")
load_element(credits, s);
else if(type == "Cash")
load_element(cashs, s);
else if(type == "Check")
load_element(checks, s);
else
throw;
}
}
};
int main() {
std::istream& file = std::cin;
Data d(file);
std::cout << "credits: " << d.credits.size() << '\n';
std::cout << "cashs: " << d.cashs.size() << '\n';
std::cout << "checks: " << d.checks.size() << '\n';
}
运行它:
./test < input.txt
input.txt
包含您帖子中的 4 个输入行。
Output:
credits: 2
cashs: 1
checks: 1
然而,英语中的现金不可数,在编程中,人们喜欢区分标量和向量/容器,因此现金向量的后缀为s
。 我的一些同事 go 只对所有容器使用后缀s
,而不管英语的任意不规则规则,例如标量的currency
和向量的currencys
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.