void main(){
/* This string needs to be printed without the '%' and in segments. */
char str[] = "Oct: %o Dec: %d Roman: %r";
int i = 0;
while (str[i] != '\0'){
/* When I run this nested loops, for some reason they don't stop at '\0'. */
while (str[i] != '%'){
printf("%c", str[i++]);
}
if (str[i] == '%')
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
您正在尝试打印字符串中的所有字符,省略任何%字符.你不需要内循环,而内循环是你所有困境的原因.内部循环将超出字符串的末尾,因为它不测试空终止字符.
简单的解决方案是用if语句替换内部循环.我们的想法是遍历整个字符串,并打印任何不是的字符%.
int i = 0;
while (str[i] != '\0')
{
if (str[i] != '%')
printf("%c", str[i]);
i++;
}
Run Code Online (Sandbox Code Playgroud)
虽然我可能用指针写这个:
const char *p = str;
while (*p)
{
if (*p != '%')
printf("%c", *p);
p++;
}
Run Code Online (Sandbox Code Playgroud)
另外,您的main函数具有非标准声明.对于main不希望处理参数的C ,您的主要应该是:
int main(void)
Run Code Online (Sandbox Code Playgroud)