Count capital letters from file c++

841 Views Asked by At
// 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 ();
}

It shows that there are occurences of capital letters. sometimes even 3 in a line. it doesn't add to the uppercase variable though.

2

There are 2 best solutions below

0
On BEST ANSWER

You are overwriting the value of uppercase variable on the next iteration: uppercase = Count(str[i]);. Just use += instead and remove those if (Count(str[i]) == X) uppercase++;

Additionally, that array of 1001 strings, of which you only use the first entry, isn't needed at all. You can just declare string str and replace str[i] with str inside main.

0
On

In case others may be searching for the title of this thread, here is the solution using the algorithm functions and streams.

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

Using the std::count_if algorithm, the file can be read in, using the stream iterators and each character read is sent to the lambda function.

In the lambda function, it is checked to see if the character is a upper case. The std::count_if will then return the count.