c++ - char array outputting as weird symbols -


so ive been learning classes, , in main function when run it, shows character array members incorrectly.

main program:

#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; // should output correctly, shows '♦'     return 0; } 

output:

 account info:     account holder :     account number :♦     balance :10000 ♦ 

whats weird using cout<< directly on char array num shows '♦'. when copy char num [] = "2435457" new program like:

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

it works correctly. edited : here header "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 

and "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; } 

your problem in constructor thought.

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

strcpy's reference says:

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

so got 2 parameters switched, you're copying uninitialized member array char pointer. since member array uninitialized @ point reading undefined behavior. should switch them:

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

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -