Hello guys. As a beginner, I am going to ask a beginner question. I am trying to do a program that takes a txt file and counts the occurrences of each character. Then it gives the output mapping the count of each char. I did this program in Visual Basic, but somebody told me it was more reliable to do it in C++. I need at least the info for the algorithm (how to do it) and the libraries I have to use.
First of all, VB will not be less reliable in this task than C++ - this is a pretty basic thing that any language can do. Reliability depends on the programmer, not the language.
If you have already written this in VB, the algorithm should be almost exactly the same regardless of the language.
C:\..\lettercounter\counter.cpp(50) : error C2039: 'push_back' : is not a member of 'basic_string<char,struct std::char_traits<char>,class std::allocator<char> >'
Error executing cl.exe.
// count letters 'a' to 'z' in string s
void countLetters( string s )
{
int pos, sum = 0;
char m;
// only a to z
for( m = 97; m < 123; m++ )
{
// start with index = 0
pos = s.find( m, 0 );
while( pos != string::npos )
{
// adjust index up
pos = s.find( m, pos+1 );
// total up this character
sum++;
}
if ( sum > 0)
{
cout << m << " = " << sum << endl;
}
sum = 0;
}
}
int main()
{
char c;
string str1;
ifstream is;
// open this text file, or replace with a text file you have ...
is.open("Microwave.txt");
// loop while extraction from file is possible
while ( is.good() ) {
// get character from file
c = is.get();
cout << c;
// build string with all lower case characters
c = tolower( c );
str1.push_back( c );
}
cout << endl << endl;
cout << str1 << endl;
// count letters a to z
countLetters(str1);
C:\Documents and Settings\Administrator.USER-58584AB94D\My Documents\C++ FILES\LetterCounter\Counter.cpp(50) : error C2664: 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &__thiscall std::basic_string<char,s
truct std::char_traits<char>,class std::allocator<char> >::append(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &)' : cannot convert parameter 1 from 'char' to 'const class std::basic_string<char,struc
t std::char_traits<char>,class std::allocator<char> > &'
Reason: cannot convert from 'char' to 'const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >'
No constructor could take the source type, or constructor overload resolution was ambiguous
Error executing cl.exe.
Well, by looking up the reference (http://www.cplusplus.com/reference/string/string/append.html) instead of asking questions you'd see that one overload of append() takes an integer, which in this case should be 1, and a char, which should be whatever you need it to be.