Read text file into vector (double, double, string)? C++ -
i have text format uses latitude, longitude , name of location , example:
41.3333 34.3232 old building i have read text file (from command line), split each line white space, use stod convert lat , long double, read whole file vector or list.
this stuck on:
#include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; class distance{ public: double x; double y; string location; }; int main(int argc, char *argv[]){ // if user didn't provide filename command line argument, // print error , exit. if (argc <= 1){ cout << "usage: " << argv[0] << " <filename>" << endl; exit(1); } char *pfilename = argv[1]; string buf; // have buffer string stringstream ss(argv[1]); // insert string stream vector<string> tokens; // create vector hold our words while (ss >> buf) tokens.push_back(buf); } question:
- could have insight on how proceed implementation?
answer: here need @ each line in file , split them whitespace store file in vector are. first number of text file latitude, second longitude, , third (string) location.
these general points whenever end using c++ :-
avoid pointers if can. prefer references or composite classes string in place of char *.
the c++ reference online can find out correct usage easily.
gdb can in of cases such problems in question.
as suggested in comments , have read file in string stream first , can parse it. have not compiled code below hope gives idea how this.in case, file standard input. can read in following manner :-
char buffer[1000]; // assumine each line of input not more while(cin.getline(buffer , 1000)) // constant 1000 can moved macro { // cin not eat newline character. have make work cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); //discard characters until newline found stringstream ss(buffer); // insert string stream vector<string> tokens; // create vector hold our words string buf ; distance distance ; ss>>buf; distance.x = stod(buf); tokens.push_back(buf); ss>>buf; distance.x = stod(buf); tokens.push_back(buf); ss>>buf; distance.x = buf; tokens.push_back(buf); }
Comments
Post a Comment