从.txt文件中读取字母和数字 [英] Reading letters and numbers from .txt file

查看:601
本文介绍了从.txt文件中读取字母和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在我的HW中犯了一个错误,而不是.txt文件中的字母。我有麻烦计数字,因为我困惑与字之间的空间。如何更改此代码来计算字而不是字母?非常感谢您的帮助。

推荐答案

此代码单独计算每个字。如果单词的第一个字符是数字,则假定整个单词为数字。

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

这篇关于从.txt文件中读取字母和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆