Oct 15, 2009 at 10:16am UTC
I am having a problem where cant pass all my keyboard input into a function using character array and returning it as a character array.
HEre is my code.I am using visual C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream.h>
#include <iomanip.h>
#include <string>
class CAT
{
public :
CAT() {}
~CAT() {}
void Setname(char name) { Name=name;}
char Getname(){ return Name;}
private :
char Name;
};
int main()
{
CAT Litter[3];
int i;
char name,*iname=&name;
for (i = 0; i < 3; i++)
{
cin>>name;
cin.ignore (1000,'\n' );
Litter[i].Setname(*iname);
}
for (i = 0; i < 3; i++)
{
cout<<"Cat #" <<i+1<<": " ;
cout<<Litter[i].Getname()<<endl;
}
return 0;
}
liao
hung
fei
Cat #1: l
Cat #2: h
Cat #3: f
Help provided will be appreciated. Thank you.
Last edited on Oct 15, 2009 at 10:20am UTC
Oct 15, 2009 at 10:32am UTC
char name
= 1 character.
Change it to a string, char* or char array and it should work.
Oct 15, 2009 at 10:43am UTC
If i change all
char name
to
char * name
. The program ended in the middle process.
Then, i try with char array as the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream.h>
#include <iomanip.h>
#include <string>
class CAT
{
public :
CAT() {}
~CAT() {}
void Setname(char name[50]) { Name[50]=name[50];}
char Getname(){ return Name[50];}
private :
char Name[50];
};
int main()
{
CAT Litter[3];
int i;
char name[50];
for (i = 0; i < 3; i++)
{
cin>>name;
cin.ignore (1000,'\n' );
Litter[i].Setname(name);
}
for (i = 0; i < 3; i++)
{
cout<<"Cat #" <<i+1<<": " ;
cout<<Litter[i].Getname()<<endl;
}
return 0;
}
ng
shi
wei
Cat #1: ?
Cat #2: ?
Cat #3: ?
Why become like this one ? Any other solution ?
Last edited on Oct 15, 2009 at 10:45am UTC
Oct 15, 2009 at 11:14am UTC
Name[50] = name[50];
return Name[50];
Your array will have 50 [] . Indexing starts at 0 and ends at 49 . You're trying to access 50 . Also.. that is still one letter only. Why not just use a string? It's much easier to use in your instance.
Oct 15, 2009 at 1:11pm UTC
Where should i put the delete name;
?
At the end of the program or after the loop ?
I tried to put it before return 0;
. Then, debug error occurred whenever the delete name;
is called. the Debug Error says "DAMAGE:After Normal block (#50) at 0x007C1890 ". Why like this one ?
Oct 15, 2009 at 1:20pm UTC
If i din put the delete name;
, the program runs smoothly. How come one ? Should be needed to put it in right ?
Oct 15, 2009 at 4:17pm UTC
Ugh, you've got big problems.
Use std::string if you want to hold strings. Otherwise your C-style char* string technique is totally wrong.
Oct 16, 2009 at 4:02am UTC
Means where should i make the correction ?
Please guide me...