c++ - Reading letters and numbers from .txt file -


i program reads letters , numbers input being used. dont know how implement .txt file. code:

    #include <iostream>     #include <string>     using namespace std;      int main()     {       char ch;         int countletters = 0, countdigits = 0;          cout << "enter line of text: ";         cin.get(ch);          while(ch != '\n'){             if(isalpha(ch))                 countletters++;             else if(isdigit(ch))                 countdigits++;             ch = toupper(ch);             cout << ch;             //get next character             cin.get(ch);         }          cout << endl;         cout << "letters = " << countletters << "      digits = " << countdigits << endl;          return 0;     } 

i made mistake in hw suppose count words instead of letters .txt file. im having trouble counting words because confused space between words. how change code count words instead of letters? appreciate help.

this code counts each word separately. if first character of "word" number, assumes entire word numeric.

#include <iterator> #include <fstream> #include <iostream>  int main() {     int countwords = 0, countdigits = 0;      ifstream file;     file.open ("your_text.txt");     string word;      while (file >> word) {        // read text file word-by-word         if (isdigit(word.at(0)) {             ++countdigits;         }         else {             ++countwords;         }         cout << word << " ";     }      cout << endl;     cout << "letters = " << countletters << "      digits = " << countdigits << endl;      return 0; } 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -