c++ - parsing a text file with first line all 1's and second line all 2's -
i have created program take file read text file line-by-line, , separate out individual words in each line (as separated blanks). want able edit code tokens first line 1's , tokens second line 2's if 1 me please down below code:
#include <iostream> using std::cout; using std::endl; #include <fstream> using std::ifstream; #include <cmath> #include <string> const int max_chars_per_line = 512; const int max_tokens_per_line = 20; const char* const delimiter = " "; using namespace std; int main() { string filename; // create file-reading object /*std::ifstream file1("file1.txt", ios_base::app); std::ifstream file2("file2.txt"); std::ofstream combinedfile("combinedfile.txt"); combinedfile << file1.rdbuf() << file2.rdbuf();*/ ifstream fin; //enter in file name combinedfile.txt cout <<"please enter file name (including .txt)"; cin >> filename ; fin.open(filename); // open file if (!fin.good()) return 1; // exit if file not found // read each line of file while (!fin.eof()) { // read entire line memory char buf[max_chars_per_line]; fin.getline(buf, max_chars_per_line); // parse line blank-delimited tokens int n = 0; // for-loop index // array store memory addresses of tokens in buf const char* token[max_tokens_per_line] = {}; // initialize 0 // parse line token[0] = strtok(buf, delimiter); // first token if (token[0]) // 0 if line blank { (n = 1; n < max_tokens_per_line; n++) { token[n] = strtok(0, delimiter); // subsequent tokens if (!token[n]) break; // no more tokens } } // process (print) tokens (int = 0; < n; i++) // n = #of tokens cout << "token[" << << "] = " << token[i] << endl; cout << endl; } system("pause"); return 0; } so output should this:
token[1] = token[1] = course token[1] = provides token[1] = detailed token[1] = coverage token[1] = of token[1] = token[1] = concepts token[1] = , token[1] = syntax token[2] = coverage token[2] = includes token[2] = inheritance, token[2] = overloaded token[2] = operators, token[2] = overloaded token[2]= default token[2] = operators,
if want separate words 2 containers such first contains words first line, , second contains words second line, can use vectors store them , string streams extract words line of text:
#include <sstream> #include <string> #include<vector> #include<fstream> using namespace std; int main() { ifstream infile("test.txt"); string line; string word; vector< vector<string> > tokens(2); (int ix = 0; ix < 2; ++ix) { getline(infile, line); istringstream iss(line); while(iss >> word) tokens[ix].push_back(word); } } here, tokens[0] vector containing words first line, , tokens[1] contains words second line.
Comments
Post a Comment