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

Reading letters and numbers from .txt file

本文关键字:数字 读取 txt 文件      更新时间:2023-10-16

从正在使用的输入中读取字母和数字的程序。但我不知道如何实现这到。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文件中计算单词而不是字母。我数单词有困难,因为我搞不清单词之间的空格。我怎样才能改变这个代码来计算单词而不是字母呢?

此代码分别计算每个单词。如果"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;
}