char数组输出为奇怪的符号

时间:2015-07-08 21:40:32

标签: c++ arrays

所以我一直在学习类,在我运行它的主函数中,它会错误地显示字符数组成员。

主程序:

#include <iostream>
#include "account.h"
#include "account.cpp"
using namespace std;
int main(){

    char num [] = "2435457";
    char name [] = "BOB JOE";
    account bob(10000, num, name );
    bob.show_account();
    cout << num; // this should output correctly, but shows the '♦'
    return 0;
}

输出:

ACCOUNT INFO:
    Account holder :
    Account number :♦
    Balance :10000
♦

奇怪的是,直接在char数组cout<<上使用num会显示'♦'。 当我将char num [] = "2435457"复制到新程序中时:

#include <iostream>    //including all the same headers does not affect
#include "account.h"   //the output
#include "account.cpp" 
using namespace std;
int main(){
    char num [] = "2435457";
    cout << num;
    return 0;
}

它正常工作。 编辑: 这是标题“account.h”

#ifndef BANK_H_
#define BANK_H_
using namespace std;

class account {
    static const int NMAX = 20, AMAX = 10;
    private:
        double balance;
        char account_number [AMAX];
        char account_holder [NMAX];
    public:
        account(double BAL, char acct [], char name []);
        void show_account();
        void deposit(double money);
        void withdrawl(double money);
};
#endif

和“account.cpp”

#include "account.h"
#include <iostream>
#include <cstring>
using namespace std;

account::account(double BAL, char acct[], char name[]){
    strcpy(name, account_holder);
    strcpy(acct, account_number);
    balance = BAL;
}

void account::show_account(){
    cout << "ACCOUNT INFO :"<<endl;
    cout << "\tAccount holder :";print(account_holder);
    cout << "\n\tAccount number :";print(account_number);
    cout << "\n\tBalance :"<<balance<<endl; 
}

void account::deposit(double money){
    balance += money;
} 

void account::withdrawl(double money){
    balance -= money;
}

1 个答案:

答案 0 :(得分:2)

你的问题就像我想的那样在构造函数中。

account::account(double BAL, char acct[], char name[]){
    strcpy(name, account_holder);
    strcpy(acct, account_number);
    balance = BAL;
}

strcpy&#39; reference说:

char* strcpy( char* dest, const char* src );

所以你切换了2个参数,你将从未初始化的成员数组复制到你的char指针。由于成员数组在此时未初始化,因此读取它是未定义的行为。你应该切换它们:

account::account(double BAL, char acct[], char name[]){
    strcpy(account_holder, name);
    strcpy(account_number, acct);
    balance = BAL;
}