Count words in each line of text file in c++ -
i open txt file using argc, argv, , getline. did properly, have number of words per line (the number of lines not known before) , must output them in reverse. meaning bottom line top line. appreciated. code outputs number of words in file:
#include <iostream> #include <fstream> #include <cstring> using namespace std; int main(int argc, char *argv[]) { if(argc < 1){ cerr << "usage: " << argv[0] << "filename.txt" << endl; } ifstream ifile(argv[1]); if(ifile.fail()){ cerr << "could not open file." << endl; return 1; } int n; ifile >> n; cout << n; int numberofwords = 0; string line; for(int = 0; <= n; i++){ getline(ifile, line); cout << line << endl; } size_t i; if (isalpha(line[0])) { numberofwords++; } (i = 1; < line.length(); i++) { if ((isalpha(line[i])) && (!isalpha(line[i-1]))) { numberofwords++; } } cout<<"the number of words in line : "<<numberofwords<<endl; return 0; }
to find number of words per line use std::getline()
iterate on each line , use std::stringstream
extract each chunk of whitespace-separated input. iterate on each chunk of input , check see if each character alphabetic:
int numberofwords = 0; (std::string line, word; std::getline(ifile, line); ) { std::istringstream iss(line); while (iss >> word) { bool alpha = true; (char c : word) if (!std::isalpha(c)) alpha = false; if (alpha) ++numberofwords; } std::cout << "number of words on line: " << numberofwords << std::endl; numberofwords = 0; }
Comments
Post a Comment