C++ homework, finding a letter from a file

Write a program which asks user to enter a string and that string saves in a .txt file. After the file has been saved your program must count how many time letter 'a' has been reapeated ?

Use fstream, string, and cctype libraries to make your jobe easier.

I wrote following code

#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <cstdlib>

using namespace std;

int main(void)
{
    string input, exit;
    int let_a = 0;;
    fstream text("test.txt", ios::in | ios::out | ios::app );

    cout << "Enter string: ";
    cin  >> input;

    if (!text)
    {
        cout << "Error at stream opening" << endl;
        system("PAUSE");
        exit(EXIT_FAILURE);
    }

    text << input;

    while ( !text.eof() )
    {
        while ( getline(text, exit) )
                {
                    for (int i = 0; i < exit.length(); i++)
                    {
                            if ( toupper(exit) == 'A')
                            {
                                let_a++;
                            }
                    }
                }
        }
     text.close();

    cout << "total A: " << let_a << endl;

    system("PAUSE");
    return 0;
}

I googled and also asked my friends but nobody can find an error :smiley:

Read this and try again:

1 Like