I wrote a template function to read in string or numeric data from files and save data in row vectors or int / double. Then I use the data to perform calculations with another code that I wrote.
Advance apologies because I think this is a simple question ... I cannot read in string data where there is a space ... For example, first and last name. When I want Tom Smith, I only get Tom.) From googling, it seems the problem is → and that I should use getline instead. I tried replacing -> getline (test, 100), but I get an error like "no match for calling in std :: basic_istringstream ..." (error: there is no corresponding function for calling "std :: basic_ifstream> :: getline (double & )))
I would be very grateful if someone could fix me! I just can't seem to have my head around the streams!
This is sample data and my code. I configured it for the lines here.
labelInFile // Identifier of the subset of data for one vector
'Tom Smith' 'Jackie Brown' 'John Doe' // These names must be in the form of elements in the vector
#include <algorithm> #include <cctype> #include <istream> #include <fstream> #include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; template<typename T> void fileRead( std::vector<T>& results, const std::string& theFile, const std::string& findMe, T& test ) { std::ifstream file( theFile.c_str() ); std::string line; while( std::getline( file, line ) ) { if( line == findMe ) { do{ std::getline( file, line, '\'' ); std::getline( file, line, '\''); std::istringstream myStream( line ); myStream >> test; results.push_back( test ); } while ( file.get() != '\n' ); } } } int main () { const std::string theFile = "test.txt"; // Path to file const std::string findMe = "labelInFile"; std::string test; std::vector<string> results; fileRead<std::string>( results, theFile, findMe, test ); cout << "Result: \n"; std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n")); return 0; }
source share