0

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;
ildjarn
  • 62,044
  • 9
  • 127
  • 211
LegItJoe
  • 15
  • 2
  • 6
  • What are the types of `cAddress`, `cFirst`, and `cSur`? `char[]`? `char*`? `string`? – Mooing Duck May 29 '12 at 23:35
  • 4
    On a side note, if you're working in C++, there's usually very little reason to use the old C-style functions like `strcpy`. You should investigate `std::string` instead, as it's much cleaner. – Oliver Charlesworth May 29 '12 at 23:36

3 Answers3

2

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.

Ansari
  • 8,168
  • 2
  • 23
  • 34
  • cAddress, cFirst, and cSur are char arrays – LegItJoe May 29 '12 at 23:39
  • Exactly, and when you add a `\0` character anywhere in the char array, that signifies "end of string." So remove that line and you should be fine :) – Ansari May 29 '12 at 23:41
  • thank you. I tried removing the line and putting this in place strcpy(cSur,cAddress + i + 1); if(cAddress[i] == '@') cSur[i] = '\0'; so that when the asterics is read the program realizes that this is the end of your surname. however this still doesn't work. so for an address like john.smith@hotmail.com, how could I extract smith? – LegItJoe May 29 '12 at 23:45
  • @LegItJoe: If you want to find the @ in the name, you'll have to write a line to _find_ that first, similar to what you did with finding first/lastname seperators. – Mooing Duck May 29 '12 at 23:55
2

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0
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.

walrii
  • 3,472
  • 2
  • 28
  • 47