C++ String Problem

Status
Not open for further replies.

Baez

Admin / Dev
Staff member
Messages
6,990
Location
Toronto, Canada
Alright I'm having trouble with this school assignment. Im on the last step and cannot figure out why it isnt working so hopefully u can tell me whats wrong. This is the code:


void Account::getFirstName(char st[])
{
int i = 0;

strcpy(st, customer);
while (st != ',')
{
i++;
}

i++;
while (st != ',')
{
strcpy(st, customer);
i++;
}
st='\0';
}

Ok let me explain. I have a string with this:

Smith,Ralph,Toronto,656-894-8574

So it goes through each letter to check if its a comma and if not keep going.

The purpose is to get rid of the last name and end chars and only keep the first name, which in this case would be Ralph without any commas. I have looked at this logic for a long time but cannot figure out where Im going wrong.

It looks so simple. But instead, I end up with Smith,Ralph left instead of only Ralph. But I don't know why it is still grabbing Smith with it.

Thanks for Your Help

Chris
 
I think it's ok to use functions in the C library. Why not?.. If the assignment wanted an implementation of any of the fundamental string functions, it could've asked for them. Or it could've said "do not use any functions other than user defined functions"..

That being said, take a look at the strtok function. You'll be done in no time :)..

http://www.cplusplus.com/ref/cstring/strtok.html

In fact, there is similar source code in the link I gave..
 
TheHeadFL said:
string class != string functions

Of course it isn't. But how is that applicable to this thread?....

Anyways, I just got home. Here's the code snippet you need..

Code:
char * getName(char * pStr)
{
    strtok(pStr, ",");
    return strtok(NULL,",");
}

Use it small function in whatever main() you have, and you should be good to go :)..

Code:
#include <stdio.h>
#include <string.h>

char * getName(char * pStr);

int main ()
{
  char str[] ="Smith,Ralph,Toronto,656-894-8574";
  printf("\r\n%s\r\n", getName(str));
  return 0;
}
 
Because the guy suggested he use the string classes which implies he would be using the standard template library string class.

Using the C libraries is not the same thing at all.
 
Think it was another guy talking about the string class.. cvb724 seems to be asking about the C libraries since he was talking about sscanf and such. And he does have a character array.

Of course, his "function" definition is still in C++ form..........
 
Status
Not open for further replies.
Back
Top Bottom