我正在嘗試創建一個計數器來計算字串中“?”之前的字符數。我在使用 strcmp 終止 while 回圈并最終出現分段錯誤時遇到問題。這是我所擁有的:
void printAmount(const char *s)
{
int i = 0;
while ( strcmp(&s[i], "?") != 0 ) {
i ;
}
printf("%i", i);
}
uj5u.com熱心網友回復:
不要strcmp用于這個。只需s直接使用下標運算子即可。
例子:
#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
}
或使用strchr
#include <string.h>
void printAmount(const char *s) {
char *f = strchr(s, '?');
if (f) {
printf("%td", f - s);
}
}
uj5u.com熱心網友回復:
strcmp()比較字串,而不是字符。因此,如果您輸入的內容類似于"123?456",則您的邏輯不起作用,因為"?" != "?456". 因此,您的 while 回圈永遠不會終止,并且您開始使用字串之外的內容。
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
}
}
uj5u.com熱心網友回復:
除非您有非常奇怪或特殊的要求,否則正確的解決方案是:
#include <string.h>
char* result = strchr(str, '?');
if(result == NULL) { /* error handling */ }
int characters_before = (int)(result - str);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427176.html
