Good morning. I'm trying to convert this into a C++ style program:
Code:
#include <iostream>
#include <string>
const int MAXSIZE = 15;
using namespace std;
unsigned int c_in_str(const char *str, char ch);
int main(void)
{
char mmm[MAXSIZE] = "minimum";
char *wail = "ululate";
unsigned int ms = c_in_str(mmm, 'm');
unsigned int us = c_in_str(wail, 'u');
cout << ms << " m characters in " << mmm << endl;
cout << us << " u characters in " << wail << endl;
return 0;
}
unsigned int c_in_str(const char *str, char ch)
{
int count = 0;
while(*str)
{
if(*str == ch)
count++;
str++;
}
return count;
}
g++ complains I'm using char * in this case
Code:
#include <iostream>
#include <string>
using namespace std;
unsigned int c_in_str(const string str, char ch);
int main(void)
{
string mmm = "minimum";
string wail = "ululate";
unsigned int ms = c_in_str(mmm, 'm');
unsigned int us = c_in_str(wail, 'u');
cout << ms << " m characters in " << mmm << endl;
cout << us << " u characters in " << wail << endl;
return 0;
}
unsigned int c_in_str(const string str, char ch)
{
int count = 0;
int i;
while(str[i] != '\0')
{
if(str[i] == ch)
count++;
str[i++];
}
return count;
}
in this case, valgrind complains I'm not setting a size to mmm and wail.
Code:
thames@semaht ~/C++/Strings $ valgrind ./strgfun
==3259== Memcheck, a memory error detector
==3259== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==3259== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==3259== Command: ./strgfun
==3259==
==3259== Use of uninitialised value of size 8
==3259== at 0x400E58: c_in_str(std::string, char) (strgfun.cpp:26)
==3259== by 0x400CA2: main (strgfun.cpp:13)
==3259==
==3259== Use of uninitialised value of size 8
==3259== at 0x400E19: c_in_str(std::string, char) (strgfun.cpp:28)
==3259== by 0x400CA2: main (strgfun.cpp:13)
==3259==
==3259== Use of uninitialised value of size 8
==3259== at 0x400E58: c_in_str(std::string, char) (strgfun.cpp:26)
==3259== by 0x400CD5: main (strgfun.cpp:14)
==3259==
==3259== Use of uninitialised value of size 8
==3259== at 0x400E19: c_in_str(std::string, char) (strgfun.cpp:28)
==3259== by 0x400CD5: main (strgfun.cpp:14)
==3259==
3 m characters in minimum
2 u characters in ululate
==3259==
==3259== HEAP SUMMARY:
==3259== in use at exit: 0 bytes in 0 blocks
==3259== total heap usage: 2 allocs, 2 frees, 64 bytes allocated
==3259==
==3259== All heap blocks were freed -- no leaks are possible
==3259==
==3259== For counts of detected and suppressed errors, rerun with: -v
==3259== Use --track-origins=yes to see where uninitialised values come from
==3259== ERROR SUMMARY: 30 errors from 4 contexts (suppressed: 2 from 2)