David Roberts
David Roberts

Reputation: 145

Counting characters in a file stream

I'm trying to make a function how_many(), which counts the number of characters of a certain type, say "\n" or ",", in a file stream. Here is my (failed) attempt:

int how_many(char mychar, anifstream myfile){
    int result;
    while(!myfile.eof())
    {
       if(myfile.get()==mychar){result=result+1;}
    }
    myfile.close(); // Closes the filestream "my file"
    return result; 
}

First question: is "\n" a character or a string? (If so, then I should make the first input a string instead of a character)

Second question: can you explain the resulting error message? (or alternatively, directly point out the misuse of syntax in my code):

 warning: result of comparison against a string literal is unspecified
  (use strncmp instead) [-Wstring-compare]
 note: candidate function not viable: no known conversion from 'const char [2]' to
  'char' for 1st argument

Upvotes: 0

Views: 781

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57698

You may want to make a histogram, while you are reading the file:

std::vector<char> character_counts(256); // Assuming ASCII characters

// ...

char c;
while (cin >> c) // The proper way to read in a character and check for eof
{
  character_counts[c]++; // Increment the number of occurances of the character.
}

In the case you posted, you could find the number of '\n' by:

cout << "Number of \'\\n\' is: " << character_counts['\n'] << endl;

Upvotes: 0

P0W
P0W

Reputation: 47794

'\n' is a char, whereas "\n" is a string literal (of type const char[2] last one for null )

For counting prefer algorithm

#include <algorithm>
#include <iterator>
//..

std::size_t result = std::count( std::istream_iterator<char>(myfile), 
                                 std::istream_iterator<char>(),
                                  mychar 
                                ) ;

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

"\n" is a string literal that has type const char[2] and contains two characters: '\n' and '\0'.

'\n' - is an escape character literal that has type char.

Take into account that variable result in your function was not initialized.

Upvotes: 1

Related Questions