Skip to content

Instantly share code, notes, and snippets.

@triztian
Last active May 29, 2018 04:50
Show Gist options
  • Save triztian/5bf71e95911df4a44036e999de97ae79 to your computer and use it in GitHub Desktop.
Save triztian/5bf71e95911df4a44036e999de97ae79 to your computer and use it in GitHub Desktop.
A simple gist showing processing of a textfile
#include <set>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
struct user {
std::string name;
std::string email;
std::string password;
};
// overload the "<" operator so that a user type can be used
// in a `std::set`
inline bool operator<(const user& x, const user& y) {
return x.email < y.email && x.name < y.name;
}
// declare the prototype of the function
std::set<user> readFile(const std::string&);
int main(int argc, char **argv) {
if (argc < 2) {
std::cout << "ERROR: file path missing" << std::endl;
return 1;
}
std::set<user> users = readFile(std::string(argv[1]));
std::cout << "Numero Usuarios: " << users.size() << std::endl;
for (auto user : users) {
std::cout << "Nombre: " << user.name << std::endl;
std::cout << "Mail: " << user.email << std::endl;
std::cout << std::endl;
}
return 0;
}
/**
*
*/
std::set<user> readFile(const std::string& filePath) {
std::ifstream file(filePath);
std::set<user> users;
if (!file) {
return users;
}
std::string line;
while (std::getline(file, line)) {
// skip if empty
if ( line.empty() ) {
continue;
}
std::istringstream linestream(line);
user u = { "", "", "" };
if ( !(linestream >> u.name) ) {
continue;
}
if ( !(linestream >> u.email) ) {
continue;
}
if ( !(linestream >> u.password) ) {
continue;
}
users.insert(u);
}
file.close();
return users;
}
USUARIO_NOM_1 user1@example.com USUARIO_CONTRASENYA_1
USUARIO_NOM_2 user2@example.com USUARIO_CONTRASENYA_2
USUARIO_NOM_4 user4@example.com
USUARIO_NOM_3 user3@example.com USUARIO_CONTRASENYA_3
USUARIO_NOM_4 user4@example.com USUARIO_CONTRASENYA_4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment