1
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++;
    }    
}
4

5 回答 5

5

您正在尝试打印字符串中的所有字符,省略任何%字符。你不需要一个内部循环,而那个内部循环是你所有麻烦的原因。内部循环将超出字符串的末尾,因为它不测试空终止字符。

简单的解决方案是用if语句替换内部循环。这个想法是遍历整个字符串,并打印任何不是%.

int i = 0;
while (str[i] != '\0')
{
    if (str[i] != '%')
        printf("%c", str[i]);
    i++;
}    

虽然我可能会使用指针来写这个:

const char *p = str;
while (*p)
{
    if (*p != '%')
        printf("%c", *p);
    p++;
}    

顺便说一句,您的main函数具有非标准声明。对于main不希望处理参数的 C,您的 main 应该是:

int main(void)
于 2013-07-05T12:00:49.593 回答
1

问题是一旦你到达这里:

 Oct: %o Dec: %d Roman: %r
                         ^

内部的 while 循环将永远保持旋转(您可以通过删除 来验证r它会按原样停止)。

要解决此问题,您可以替换为while (str[i] != '%')if (str[i] != '%')而不必触摸原始字符串。

还有一些评论:

main将from的返回类型更改voidint。并在 .return 0;的右大括号之前添加main。这是一个典型的 C 约定,它向操作系统指示运行是否成功(0 表示正常,非零表示存在问题)。

如果你用警告编译你的代码,你应该得到一个警告(启用它们,因为一些错误并不总是那么明显,警告可以很好地通知你)。

使用我的 GCC 编译器,我得到了warning: return type of ‘main’ is not ‘int’ [-Wmain]. 我用-Walland-Wextra标志运行它。

于 2013-07-05T12:02:31.043 回答
0

你应该这样做——>

   while (str[i] != '\0'){ 
        if(str[i++] != '%') {
            printf("%c", str[i])
        }
        else {

        }
}
于 2013-07-05T12:19:59.347 回答
0

while 将跳过 '\0' 因为它不是 '%'

于 2013-07-05T11:56:17.793 回答
0

@BryanOlivier 是对的,所以

while ((str[i] != '%')&&(str[i] != '\0')){
        printf("%c", str[i++]);
    }

代替

 while (str[i] != '%'){
        printf("%c", str[i++]);
    }

尝试这个。

于 2013-07-05T12:00:29.837 回答