【发布时间】:2021-09-18 19:18:24
【问题描述】:
为什么我的程序没有进入无限循环。我没有使用'\0' 在while 循环中测试字符串结尾,而是使用0。 '\0' 和 0 在 C 语言中是否相同?
如果是,那么如果0 在字符串的中间,那么printf 应该在此处结束打印字符串。
例如printf("%s", "hello how0 are you") 应该打印 'hello how'
int main( )
{
char s[ ] = "No two viruses work similarly" ;
int i = 0 ;
while ( s[i] != 0 )
{
printf ( "%c", s[i]) ;
i++ ;
}
}
【问题讨论】:
-
以下两个有何不同?
-
printf("%s", "hello how0 are you") vs printf("%s", "hello how\0 are you") 为什么上述两种情况下的输出不同?跨度>
-
也许这不清楚:像“ABC”这样的字符串被一个空字符隐式终止,这就是你的循环结束的原因。所以在内存中“ABC”看起来像这样:
65 66 67 0,65 是A字符等的 ASCII 值。 -
@4386427 你说得对,删除评论
标签: c while-loop char printf c-strings