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

时间:2015-08-31 04:53:45

标签: c++ count

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

from itertools import cycle

for item, user in zip(ids, cycle(users)):
    my_function(item, user)

我在我的硬件中犯了一个错误我想要计算单词而不是.txt文件中的字母。我在计算单词时遇到了麻烦,因为我对单词之间的空格感到困惑。我怎么能改变这个代码来计算单词而不是字母呢?我非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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;
}