90s_Kidd
90s_Kidd

Reputation: 31

Reading letters and numbers from .txt file

I program which reads the letters and numbers from the input being used. But i dont know how to implement this to a .txt file. This is my code:

    #include <iostream>
    #include <string>
    using namespace std;

    int main()
    {
      char ch;
        int countLetters = 0, countDigits = 0;

        cout << "Enter a 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 a mistake in my HW I was suppose to count the words instead of letters from the .txt file. Im having trouble counting words because I get confused with the space between words. How could I change this code to count the words instead of letters? I really appreciate the help.

Upvotes: 1

Views: 2885

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

This code counts each word separately. If the first character of a "word" is a number, it assumes the entire word is 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 the 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;
}

Upvotes: 1

tepl
tepl

Reputation: 421

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  char ch;
    int countLetters = 0, countDigits = 0;

    ifstream is("a.txt");

    while (is.get(ch)){
        if(isalpha(ch))
            countLetters++;
        else if(isdigit(ch))
            countDigits++;
        ch = toupper(ch);
        cout << ch;
    }

    is.close();

    cout << endl;
    cout << "Letters = " << countLetters << "      Digits = " << countDigits << endl;

    return 0;
}

Upvotes: 0

Related Questions