why will strcpy only copy a limited number of elements:

640 Views Asked by At

C++ newbie here. Writing a simple program. Everything works,except when I attempt to extract firstname and surname and print these individually, the number of letters printed in surname will always be the same size as the number in firstname. So if the name is will jackson, the program will print firstname as: will and second name as: jack. How do I solve this?

here is the code

for( i = 0; i < 19; i++)
  if(cAddress[i] == ' ' || cAddress[i] == '_' || cAddress[i] == '-' || cAddress[i] == '.')
    break;

strncpy(cFirst, cAddress, i);

cFirst[i] = '\0';
cout << endl << "\n";
cout << "Your first name is " << cFirst << endl;

strcpy(cSur,cAddress + i + 1);
cSur[i] = '\0';
cout << endl;
cout << "Your surname is " << cSur << endl;
3

There are 3 best solutions below

4
On

You are adding a \0 character at the (i+1)th position - this marks the end of string, so that's all it prints. Before that line, cSur probably contains the entire surname.

0
On

Most of your code looks a lot like C -- and doesn't even take full advantage of the C standard library. In C++, I'd write something more like:

int pos = Address.find_first_of(" _-.");

std::string FirstName(Address, 0, pos);
std::string SurName(Address, pos);

If, for whatever reason, you insist on using C style strings, you might consider starting with strpbrk to find the separator.

0
On
cSur[i] = '\0';

is incorrect. i is the length of the first name. cSur is already zero terminated by strcpy.

Having explained that, Jerry Coffin's answer is what I would recommend as good c++ code.