char punct(char a[], int len) {
for (int i = 0; i < len; i++) {
if (ispunct(a[i]))
{ return i; }
return -1;
}
}
Could anyone tell me why this function is only returning -1 for every string that I hand to it? I’m writing a program to take words from a .txt file and outputting them (with a little bit of alteration) into a different .txt file, and I need to remove punctuation from the strings. However, I cannot seem to detect where the punctuation is using the ispunct() function. I even wrote my own function using all of the cases of punctuation I could imagine and it still only returns -1. Is it a problem with the function here or the strings that I am giving to it? If showing more of my code is necessary, please let me know. Thanks!
That’s because if
ispunct(a[0])returnsfalse,return -1is called.You should move the default return outside of the loop:
Note that this function only returns the first punctuation index, not all indexes. I guess you’re treating this case outside the function.