I'm trying to create a counter that counts the amount of characters in a string before "?". I have issues with using strcmp to terminate the while-loop and end up with a segmentation fault. Here's what I have:
void printAmount(const char *s)
{
int i = 0;
while ( strcmp(&s[i], "?") != 0 ) {
i ;
}
printf("%i", i);
}
CodePudding user response:
Don't use strcmp
for this. Just use the subscript operator on s
directly.
Example:
#include <stdio.h>
void printAmount(const char *s) {
int i = 0;
while (s[i] != '?' && s[i] != '\0') {
i ;
}
printf("%d", i);
}
int main() {
printAmount("Hello?world"); // prints 5
}
Or use strchr
#include <string.h>
void printAmount(const char *s) {
char *f = strchr(s, '?');
if (f) {
printf("%td", f - s);
}
}
CodePudding user response:
strcmp()
compares strings, not characters. So, if you input is something like "123?456"
, your logic does not work, because "?" != "?456"
. Thus, your while loop never terminates and you start using stuff outside the string.
void printAmount(const char * s) {
int i = 0;
for (; s[i] != '?' && s[i] != '\0'; i ) {
/* empty */
}
if (s[i] == '?') {
printf("%d",i); // the correct formatting string for integer is %d not %i
}
}
CodePudding user response:
Unless you have very strange or specialized requirements, the correct solution is this:
#include <string.h>
char* result = strchr(str, '?');
if(result == NULL) { /* error handling */ }
int characters_before = (int)(result - str);