'How to create a "X" terminated string in C?
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);
}
Solution 1:[1]
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
}
}
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BitTickler |
| Solution 2 | Lundin |
