Search code examples
c++filecapitalizationletteralphabet

Count capital letters from file 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 ();
}

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


Solution

  • 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.