【问题标题】:Reading letters and numbers from .txt file从 .txt 文件中读取字母和数字
【发布时间】:2015-08-31 04:53:45
【问题描述】:

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

【问题讨论】:

  • 在网络上搜索“C++ 读取文本文件”。尝试自己做,遇到具体问题再回来。

标签: c++ count


【解决方案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;
}

【讨论】:

  • 我必须使用相同的方法来计算数字吗?目前此方法也将数字视为单词。
  • 你确定你不会有任何混合数字字母的单词吗?是的,这目前计算每个单词,无论是“数字”还是其他。
  • 我必须分别计算单词和数字,这就是我卡住的地方。我很困惑,以为我必须计算单个字母和数字。我们的教授说我们不需要阅读诸如 X2 或 student123 之类的字母组合。但相反:猫在 [there]\n 10 20 3.1416,,1000\n(所有这些都在 .txt 文件中)
  • 如果第一个字母是数字,我假设单词是数字。也许这足以解决您的问题。查看我的更新答案。
  • 我从教授那里得到了关于您帮助我完成的项目的新指示。你介意帮助我吗?我真的很感激。我在一个新标题下发布了这个问题:阅读 ' 、 ' 和 ' 。 ' 作为 .txt 文件中的空格。
【解决方案2】:
#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;
}

【讨论】:

  • 非常感谢这对您有很大帮助!!!你介意回答别的吗?我的文本文件有 3 行,它们是: The cat is [there]\n 10 20 3.1416,,1000\n another cat\n 它可以完美地读取所有字母和数字,但是我将如何阅读单词而不是字母?我在我的硬件中犯了一个错误,它要求计算单词而不是字母。
猜你喜欢
  • 2021-06-10
  • 2016-05-27
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多