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

90s_Kidd

我编程从正在使用的输入中读取字母和数字。但是我不知道如何将其实现为.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;
    }

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

蒂姆·比格莱森(Tim Biegeleisen)

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章