C++ how to read what I want from a file? -
how can assign variable c++ code value structured .txt file example? if have following input.txt structured this:
<name> "john washington" <age> "24" <id> "19702408447417" <alive status> "deceased"
in c++ code if have
ifstream read("input.txt",ios::in); char name[64]; read>>name;//name point john washington string int age; read>>age;// cout<<age return 24; int id; read>>id;// cout<<id return 19702408447417 char alivestatus[32]; read>>alivestatus;//alivestatus point deceased string;
how can make work above?
as @πάντα ῥεῖ mentioned in comments, need implement parser can interpret <>
tags within file. additionally, recommend reconsidering data types.
specifically, given there's no special reason you're using char []
, please switch std::string
. don't know use case of code, if input.txt
happens contain data thats larger size of arrays, or worse if input user-controlled, can lead buffer overflows , unwanted exploits. std::string
has benefit of being standardized, optimized, more friendly char arrays, , has variety of useful algorithms , functions readily available use.
with regards text file parsing, can perhaps implement following:
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream input_file("input.txt"); std::string name_delimeter("<name> "); std::string age_delimeter("<age> "); std::string id_delimeter("<id> "); std::string alive_delimeter("<alive status> "); std::string line; std::getline(input_file,line); std::string name(line,line.find(name_delimeter) + name_delimeter.size()); // string reasons described above std::getline(input_file,line); int age = std::atoi(line.substr(line.find(age_delimeter) + age_delimeter.size()).c_str()); std::getline(input_file,line); std::string id(line,line.find(id_delimeter) + id_delimeter.size()); // example id overflows 32-bit integer // maybe representing string more appropriate std::getline(input_file,line); std::string alive_status(line,line.find(alive_delimeter) + alive_delimeter.size()); // string same reason name std::cout << "name = " << name << std::endl << "age = " << age << std::endl << "id = " << id << std::endl << "alive? " << alive_status << std::endl; }
the basis of code read file structured , construct appropriate data types them. in fact, because used std::string of data types, easy build correct output means of std::string's constructors , available functions.
maybe performing in loop, or file has several structures. approach problem, can make record
class overloads operator >>
, reads in data required.
Comments
Post a Comment