+4

[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.

c

2/21/2020 8:20:48 PM

Paul K Sadler

9 Answers

New Answer

+5

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.

+1

Have you tried if(strpbrk(...) != 0)

+1

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.

+1

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

+1

char *ptr=strpbrk(c,"%@"); if(ptr) .. else .... May This works.. Tried it? Or if(strpbrk(c, "%&@")!='\0')

+1

unsigned specialChar = 0; char *str = "A string# with$ special& characters!"; char *specialCharacters = "#$&!"; char *p = str; while ((p = strpbrk (p, specialCharacters)) != NULL){ ++p; ++specialChar; } printf ("SpecialChar = %d\n",specialChar);

+1

Did you try this : if(strpbrk(c, specialCharacters) != NULL) specialChar++;

+1

"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/

+1

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