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

标签 c++ count

我的程序从正在使用的输入中读取字母和数字。但我不知道如何将其实现到 .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 文件中的单词而不是字母。我在数单词时遇到了麻烦,因为我对单词之间的空格感到困惑。我如何更改此代码以计算单词而不是字母?非常感谢您的帮助。

最佳答案

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

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

关于c++ - 从 .txt 文件中读取字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304194/

相关文章:

c++ - 指向 CUDA 中对象指针数组的指针

mysql - 优化 mysql 查询(喜欢/不喜欢)

mysql - 如果在表中找不到记录,则显示 0 而不是空白

c++ - Windows Qt 二进制安装程序是否支持开箱即用的 DBus?

MySQL : Count row where sum of left day is less than 30

MYSQL 查询所需总计

sql - 从数据库中的表中选择计数的总和

c++ - 将文件数据读入二维数组时出现 EXC_BAD_ACCESS

c++ - std::random_device的实现方式

C++:前向声明时指针大小未知(错误 C2036)