计算文件C ++中的大写字母

问题描述

// C++ program to count the uppercase
#include<iostream> 
#include<fstream>
#include <string>
using namespace std;

// Function to count uppercase
int Count ( string str )
{
    int upper = 0;
    for (int i = 0; i < str.length(); i++) {
      if (str[i] >= 'A' && str[i] <= 'Z')
        upper++;
    }
    return upper;
}

// Driver function 
int main()
{
    //Open the file
    ifstream openedFile;

    //This is how you turn the potential file into an actualized file inside the defualt directory.
    openedFile.open ( "random words.txt" );

    string str[10001]; int i = 0;
    int uppercase = 0;
    
    while (!openedFile.eof())
    {
        getline ( openedFile,str[i],'\n');
        uppercase = Count(str[i]);
        if (Count(str[i]) == 1) uppercase++;
        if (Count(str[i]) == 3) uppercase++;
        if (Count(str[i]) == 2) uppercase++;
        cout << Count(str[i]) << "\n";
    }

    cout << "Uppercase letters: " << uppercase << endl;

    //Close the file
    openedFile.close ();
}

表明存在大写字母。有时甚至连三行。它不会添加到大写变量中。

解决方法

如果其他人可能正在搜索该线程的标题,这是使用算法函数和流的解决方案。

#include <algorithm>
#include <iterator>
#include <iostream>
#include <cctype>
#include <fstream>

int main()
{
    std::ifstream openedFile("random words.txt");
    
    std::cout << "Uppercase letters: " 
        <<  std::count_if(std::istream_iterator<char>(openedFile),std::istream_iterator<char>(),[](char ch) 
                            {return std::isupper(static_cast<unsigned char>(ch));}
                         ) 
        << "\n";
}

使用std::count_if算法,可以使用流迭代器读取文件,并将每个读取的字符发送到lambda函数。

在lambda函数中,检查该字符是否为大写。 std::count_if随后将返回计数。

,

您将在下一次迭代uppercase = Count(str[i]);上覆盖大写变量的值。只需改用+=并删除那些if (Count(str[i]) == X) uppercase++;

此外,根本不需要1001个字符串数组(仅使用第一个条目)。您只需声明string str并将str[i]替换为main内部的str