return a substring of a cstring;
I'm trying to write a function that looks for a character in an array of char, then returns the rest of the array.
I'm getting errors, and I can't figure out what I'm doing wrong.
1 2 3 4 5 6 7 8 9 10 11 12
|
const char* strfind( const char inhere, const char thisch) {
const char* found;
found = &inhere;
while ( *(found++) != thisch)
{ /* do nothing */ }
return found;
}
int main () {
char str[]= "Piss off!";
cout << strfind (str, " ") << endl; // Line 56.
}
|
My errors are:
review07-2.cpp:56: error: invalid conversion from ‘const char*’ to ‘char’
review07-2.cpp:56: error: initializing argument 2 of ‘const char* strfind(char, char)’ |
Any help would be appreciated!
const char* inhere
also change line 3.
Last edited on
Nevermind, I got it now! ^_^
1 2 3 4 5 6 7 8 9 10 11
|
const char* strfind( const char* inhere, const char thisch) {
while ( *(inhere++) != thisch)
{ /* do nothing */ }
return inhere;
}
int main () {
char str[]= "Piss off!";
cout << strfind (str, ' ') << endl;
cout << str << endl; // Just to prove str is unaffected.
}
|
Thanks hamstrman!
that function will fail spectacularly if thisch
is not in the string.
Disch, I know.
Can you think of a neater way than this?
1 2 3 4 5 6
|
const char* strfind( const char* inhere, const char thisch) {
while ( *(inhere) != thisch && *(inhere+1) != '\0')
{ inhere++; }
inhere++;
return inhere;
}
|
maybe
1 2 3
|
int i;
for(i = 0; inhere[i] != thischar && inhere[i+1] != '\0'; i++);
return i+1;
|
Topic archived. No new replies allowed.