c++程序成功构建,没有输出,只显示堆栈跟踪

c++ program successfully build, No output, only show stack trace

本文关键字:显示 堆栈 跟踪 输出 程序 成功 构建 c++      更新时间:2023-10-16

成功构建,但Netbeans Run输出堆栈跟踪

堆栈跟踪:

Frame     Function  Args
0022C694  7570EFA3  (00000108, 0000EA60, 00000000, 0022C7B8)
..............
End of stack trace

我正在逐行阅读一个文件,并使用C++类概念检查它们是否有元音。

我已经测试过在不使用C++类的情况下逐行读取文件并成功地逐行写入文件。

请帮忙指出我应该在哪里更改代码。我想是内存管理问题。

非常感谢!

#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 accpetablern";
    }
    }
    infile.close();
    outfile.close();
    return 0;
}

有几件事。第一个原因是Passwordpwd成员没有初始化,这可能会导致setPassword(...)在第一次调用时失败。您可以像这样在构造函数中初始化(为了避免混淆,重命名了参数(:

    Password(const char *apwd) : pwd(0) {
        setPassword(apwd);
    }

第二个问题是,正如你发布的那样,containsVowel已经损坏了。变量i也没有初始化,我猜应该有一个循环——看起来它被省略了。此外,德兰在答复中提到的比较也存在问题。

您也可以考虑将pwd成员设置为std::string。这会让你的生活变得更轻松,无论是在记忆管理方面,还是在寻找元音方面——我认为你可以使用str.find_first_of(...)来寻找元音,而无需自己迭代所有字符。

if(this->pwd[i]== 'a' || 'e' || 'i' || 'o' || 'u' )

应该是

if(this->pwd[i]== 'a' || this->pwd[i]== 'e' || this->pwd[i]== 'i' || this->pwd[i]== 'o' || this->pwd[i]== 'u' )

如果你这样做:

        delete []this->pwd;
        if(pwd!=NULL){
            this->pwd=new char[strlen(pwd)+1];

如果这个->pwd为NULL,会发生什么?