Finding instances of -user specified- character in file stream

Hey there,

I am working on a program that is supposed to take input from a user in the form of a single character, it is then supposed to look for instances of that character in a text file.

This is just one piece of logic in an expansive program that I won't paste here. I'll note whenever a variable is used that was created for the larger program.

At this point the build fails, because of the comparison in the FOR loop. It compares an int and a char. I know I will have to loop through my file stream and then do a comparison with the user input, but I am clueless as to how to achieve this. Sorry for the n00b question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

cout << "Please enter a letter: " << endl;

cin << userInput;
char array[100];
strcpy(array, userInput.c_str()); // converts user string into a char

inFile.open(userWord3, ios::in); // userWord3 is used in larger program. This just opens the stream.

char array2[1000];
strcpy(array2, buffer.c_str());

int count = 0;
while (!inFile.eof())
    {
        for (int i = 0; array2[i] == array; i++)
        {
            count++;
        }
    }
cout << "The character appears " << count << " times." << endl;


Any help would be much appreciated.
Last edited on
Couldn't you just use the get function for ifstream?
http://www.cplusplus.com/reference/istream/istream/get/
Hi Keene,

When I try to use cin.get I get an error, "No matching member function to call 'get'". Can you give me an example of how it would be used?

Thanks!
I figured it out. I included some of my variables for the larger program so if you get confused, just send me a private message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char array[100];
strcpy(array, editedInput4.c_str()); // converts editedInput4 into a char array
        
inFile.open(userWord3, ios::in);
        
getline(inFile, buffer, '\0');
char array2[1000];
strcpy(array2, buffer.c_str()); // converts each character in 'buffer' into a char array
int index = 0;
int count = 0;
    
while (index < 1000)
    {
    if (array2[index] == array[0])
        {
             count++;
         }
            index++;
        }
cout << "The letter " << array[0] << " appears " << count << " time(s)." << endl;
Last edited on
Topic archived. No new replies allowed.