c++ - problems with dividing the words while parsing the formatted input -
#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> int main(int argc, char *argv[]) { std::vector<std::string> vec; std::string line; std::ifstream in(argv[1]); while(!in.eof()) { std::getline(in,line); vec.push_back(line); } std::istringstream is; line = ""; for(auto a:vec) { for(auto = a.begin(); != a.end(); i++) { if(!(isspace(*i) | ispunct(*i))) line += *i; else { is.str(line); std::cout << is.str() << std::endl; line = ""; } } } std::cout << is.str() << std::endl; return 0; } i've written program takes file , puts each line in vector of strings. reads 1 word @ time element.
when i'm reading vector having trouble specifying new lines. output concatenates end of 1 line , beginning of next. how can specify there new line?
the file content i'm reading:
math 3 2 math 4 3 math 5 4 phys 3 1 math 3 1 comp 3 2 the output i'm getting:
math 3 2math 4 3math 5 4phys 3 1math 3 1comp 3 3 edit::
to clarify, vector elements constructed correctly. if print in for(auto a:vec), give me line line file. it's when try build word each char in vector. asking can specify there new line
line += a[i] does not keep adding line when hits end of 1 line.
don't do
while (!in.eof()) { ... } it not work way expect to.
instead do
while (std::getline(...)) { ... } the reason because eof flag isn't set until try read when file @ end. means loop 1 time many, trying read non-existent line add vector.
there way of separating "words" on space boundary, using std::istringstream , normal input operator >>:
std::istringstream is{a}; std::string word; while (is >> word) { // `word` }
Comments
Post a Comment