Reputation: 41
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
I am trying to read in this file in c++ but I can't figure out a proper way to do it. I need to read in each individual data point into different vectors. For example in a vector called transaction type would be Credit cash check Credit
.
This is the code I have now and it gives me really weird results
file.open(fileName);
string line;
string space;
while(getline(file,line,'\n')){
cout<<"Row: ";
while(getline(file,space,' ')){
cout<<space<<" ";
}
}
cout<<space<<" ";
return 0;```
Upvotes: 0
Views: 661
Reputation: 136266
Spaces and newlines are classified as (white)space in C++, see std::isspace. std::istream& operator>>(std::istream&, T&)
skips all whitespace, so that no special handling for spaces or newlines is required.
One example:
#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';
}
Run it as:
./test < input.txt
input.txt
contains the 4 input lines from your post.
Output:
credits: 2
cashs: 1
checks: 1
Cash in uncountable in English, however, in programming one likes to distinguish scalars and vectors/containers, hence s
suffix for a vector of cash. Some of my colleagues go as far as just using suffix s
for all containers regardless of arbitrary irregular rules of English, e.g. currency
for scalars and currencys
for vectors.
Upvotes: 2