-
String length
I have tried the following program:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
class Member
{
private:
int Age;
int l,L;
char Name[40];
public:
void SetName(char* name)
{
l= strlen(name);
cout<<"l="<<l<<endl;
for(int i=0;i<l;i++)
{
Name[i] = name[i];
cout<<"Name["<<i<<"] = "<<Name[i]<<endl;
}
cout<<Name;
for(int j=l;j<sizeof(Name);j++)
{
Name[j] = ' ';
}
}
void DisplayName()
{
L = strlen(Name);
cout<<"The length of the Name is :"<<L<<endl;
for(int y=0;y<l;y++)
{
cout<<Name[y];
}
}
void SetAge(int age)
{
Age = age;
}
void DisplayAge()
{
cout<<"Age = "<<Age<<endl;
}
};
void main()
{
char s[40];
Member Kokila;
cout<<"Please enter a name"<<endl;
cin.getline(s,40);
Kokila.SetAge(14);
Kokila.DisplayAge();
Kokila.SetName(s);
Kokila.DisplayName();
}
I have entered Tom as input. In SetName() method, the value of l =3. In DisplayName() method, the value of L = 43( ie sum of the length of Name[40] from the class member and the length of the input string). I cannot understand why .
Anybody ..can explain me...
Thanks,
Kokila.
-
If I understand your question correctly, the reason your string lenght is being displayed as 43 is because you are setting all the elements of the Name array to a space, which in ASCII text is 32. If you want to clear the array try something like:
strncpy(Name, NULL, sizeof(Name))//not sure if this will cause a stack error or not
and if that doesn't work you can always do this:
for(USHORT i=0; i<sizeof(Name); i++){
Name[i] = '\0'; //'\0' is basically a NULL value
}
Good Luck!
-
You may also want to consider memcpy. It is called like:
memcpy( tohere, thisCharacter, thisMany );
Thus, 'memcpy( myBuffer, NULL, sizeof(myBuffer) );
Quzah.
-
I edited this to change the bottom for-loop also. Should be l+1.
void SetName(char* name)
{
l= strlen(name);
cout<<"l="<<l<<endl;
for(int i=0;i<l;i++)
//To get the string terminator, should be
for(int i=0;i<=l;i++)
{
Name[i] = name[i];
cout<<"Name["<<i<<"] = "<<Name[i]<<endl;
}
cout<<Name;
for(int j=l;j<sizeof(Name);j++)
//I think this should be
for(int j=l+1;j<sizeof(Name);j++)
{
Name[j] = ' ';
}
}
//Another option is strcpy(Name,name);
-
Quote:
Originally posted by quzah
You may also want to consider memcpy. It is called like:
memcpy( tohere, thisCharacter, thisMany );
Thus, 'memcpy( myBuffer, NULL, sizeof(myBuffer) );
Quzah.
You mean memset, right? memcopy copies memory.