从 .txt 文件中读取字母和数字

Reading letters and numbers from .txt file

我编写了一个从正在使用的输入中读取字母和数字的程序。但我不知道如何将其实现到 .txt 文件中。这是我的代码:

    #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;
    }

我在我的 HW 中犯了一个错误,我应该计算 .txt 文件中的单词而不是字母。我在数单词时遇到了麻烦,因为我对单词之间的 space 感到困惑。我如何更改此代码以计算单词而不是字母?非常感谢您的帮助。

此代码分别计算每个单词。如果 "word" 的第一个字符是数字,则假定整个单词都是数字。

#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;
}
#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;
}