【问题标题】:Count capital letters from file c++计算文件c ++中的大写字母
【发布时间】:2021-01-25 15:40:36
【问题描述】:
// 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 ();
}

表示出现大写字母。有时甚至连3个。但它不会添加到大写变量中。

【问题讨论】:

  • uppercase = Count(str[i]); if (Count(str[i]) == 1) uppercase++; if (Count(str[i]) == 3) uppercase++; if (Count(str[i]) == 2) uppercase++;的目的是什么?
  • string str[10001] 你真的需要一个数组吗?
  • 如果i 永远不会改变并且没有理由保留数据,那么数组是什么?
  • 您可能永远不会看到它失败的情况,但 if (str[i] &gt;= 'A' &amp;&amp; str[i] &lt;= 'Z') 会在一个连续的块中使用 AZ 的字符集,其中 A first 和 Z last,这并不能保证。跨度>

标签: c++ file capitalization letter alphabet


【解决方案1】:

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

#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 将返回计数。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 2020-01-04
      • 2013-08-16
      相关资源
      最近更新 更多