Type Casting File Input to Vector Type in C++ -
Type Casting File Input to Vector Type in C++ -
in main function, there various vectors of different template types(float, int, char*). function called read in formatted input different files fill each vector. problem coming type conversion since
v.push_back((t)(pchar)); does not converting char* float(presumably because of decimal point).
question: there way right conversions regardless of info type long input file appropriate? (i've considered typeid(); not sold on using it)
template <class t> void get_list(vector <t> & v, const char * path) { fstream file; const char delim[1]{' '}; char line[512]; char * pchar; file.open(path, ios_base::in); if (file.is_open()) { while (!file.eof()) { file.getline(line, 512); pchar = strtok(line, delim); while (pchar != null) { v.push_back(pchar); pchar = strtok(null, delim); } } file.close(); } else { cout << "an error has occurred while opening specified file." << endl; } } this homework problem not pertain straight objective of assignment. assignment on heaps info structs/algorithm class.
indeed, can't cast string arbitrary type, you'll need code parse , interpret contents of string. i/o library has string streams that:
std::stringstream ss(pchar); t value; ss >> value; v.push_back(value); this work types have >> overload, including built-in numeric types float.
alternatively, might want rid of nasty c-style tokenisation:
t value; while (file >> value) { v.push_back(value); } or
std::copy( std::istream_iterator<t>(file), std::istream_iterator<t>(), std::back_inserter(v)); at least, alter loop to
while (file.getline(line, 512)) checking file status after reading line, don't process final line twice.
c++ casting
Comments
Post a Comment