Successfully Build, but Netbeans Run outputs stack trace
Stack trace:
Frame Function Args
0022C694 7570EFA3 (00000108, 0000EA60, 00000000, 0022C7B8)
..............
End of stack trace
I am reading a file line-by-line and check if they have vowel using C++ class concept.
I have tested read a file line-by-line and out to write a file line-by-line successfully without using C++ class.
Please help to point out where i should change my code. I guess there is memory management problems.
Thank you very much!
#include <cstdlib>
#include<fstream>
#include <iostream>
using namespace std;
class Password{
private:
char *pwd;
public:
Password(const char*pwd){
setPassword(pwd);
}
~Password(){
delete []pwd;
}
void setPassword(const char *pwd){
delete []this->pwd;
if(pwd!=NULL){
this->pwd=new char[strlen(pwd)+1];
strcpy(this->pwd,pwd);
}else{
this->pwd=NULL;
}
}
char *getPassword(){
return this->pwd;
}
bool containsVowel(){
int i,counter=0;
for(i=0;i<strlen(this->pwd);i++){
if(this->pwd[i]== 'a' || 'e' || 'i' || 'o' || 'u' )
counter++;
}
if (counter>0)
return true;
return false;
}
};
int main(int argc, char** argv) {
ifstream infile("C:/Users/user/Desktop/say.in");
ofstream outfile("C:/Users/user/Desktop/say.out");
string str;
while (getline(infile,str)){
const char *pwd=str.c_str();
Password pwdObj(pwd);
if (pwdObj.containsVowel()==true){
outfile<<"<"<<str<<"> is accpetable\r\n";
}
}
infile.close();
outfile.close();
return 0;
}
There are a couple of things. First one is that the
pwdmember ofPasswordis not initialized, which will probably causesetPassword(...)to fail on the first call. You could initialize in your constructor like so (argument renamed to avoid confusion):The second problem is that
containsVowelis quite broken as you’ve posted it. The variableiis also not initialized and I’m guessing there should be a loop — looks like it’s been omitted. Also there is a problem with the comparison that Delan has noted in his reply.You could also consider making the
pwdmember astd::string. It would make your life somewhat easier, both in terms of memory management, and finding vowels — I’m thinking you could usestr.find_first_of(...)to find the vowels without iterating through all the characters yourself.