+ 9
[Solved] I can't seem to get correct casting to use strpbrk from string.h I get a casting error.
The line in question is: /* if(strpbrk(c,specialCharacters)) specialChar++; */ c and specialCharacters are char *variable name = ... I searched here for strpbrk and did not find any post that helped.
9 Respostas
+ 6
rodwynnejones Rafik Abdelhak andriy kan Jayakrishna Mihai Apostol
Thank you all for helping me with this. I was able to get strpbrk to work once I determine how to properly pass the char array element.
The corrected line is:
If(strpbrk((char[2]){variable[i], '\0'}, specialCharacters)) specialChar++;
// char variable[50];
I did not need var c once I figured out how to properly cast.
All of your input guided me down the right path. Thanks for your help. Sorry I did not post the code, but I was working on a code coach solution and did not want to give it away since the Mod's have encouraged us not to.
+ 3
unsigned specialChar = 0;
char *str = "A string# with$ special& characters!";
char *specialCharacters = "#amp;!";
char *p = str;
while ((p = strpbrk (p, specialCharacters)) != NULL){
++p;
++specialChar;
}
printf ("SpecialChar = %d\n",specialChar);
+ 2
Have you tried
if(strpbrk(...) != 0)
+ 2
Mihai Apostol No, my research indicated it returns a Cstring (char *var) or NULL if none of the characters in str2 are found in str1 (strpbrk(str1,str2). So I am thinking that would not work.
+ 2
I was thinking that I need to set a result var to the return value and then test that in the if. I thought that because at first I tested the element of the char array like so:
If(strpbrk(variable[i], specialCharacters)) ... which produced an error
i is the iterator in the for loop.
I changed this to c with a line before the if...
const char *c = variable[i]; ... a single element of the char array
+ 2
char *ptr=strpbrk(c,"%@");
if(ptr)
..
else
....
May This works.. Tried it?
Or
if(strpbrk(c, "%&@")!='\0')
+ 2
Did you try this :
if(strpbrk(c, specialCharacters) != NULL)
specialChar++;
+ 2
"If(strpbrk(variable[i], specialCharacters)) ... which produced an error"...because strpbrk need two string (c-style strings)...but your passing a character (variable[i])...and a string...you need to use strchr.
http://www.cplusplus.com/reference/cstring/strchr/
+ 2
rodwynnejones I saw that in the string.h def and was thinking of using that. I just went back through the SL pointer lessons. I am going through a one character string to see if it contains any of a list of characters. I am trying to take a single character from a char array and turn it into a Cstring (char *ch = characterat[i]). is that possible? I would like to understand why I can't get strpbrk to work. I am new to c