gpt4 book ai didi

c - 计算空格和制表符程序的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 18:24:10 24 4
gpt4 key购买 nike

C代码

#include <stdio.h>

int main ()
{
int c , nother , new , ndigits [10] , white, tabs ;

for ( int i = 0 ; i< 10 ; i++)
ndigits[i] = 0 ;

while ( (c = getchar() )!= EOF )
{
switch (c)
{
case '0' : case '1' : case '2' :
case '3' : case '4' : case '5' :
case '6' : case '7' : case '8' :
case '9' :
ndigits[c- '0' ]++ ;
break ;

case ' ' :
printf("w"); /*to see how many spaces */
white++ ;

case '\t' :
printf("t");
tabs++;

case '\n' :
printf("n");
new++ ;
break ;

default :
nother++ ;
break ;
}
}

printf ("digits = " ) ;

for ( int i = 0 ; i < 10 ; i++ )
printf ("%d" , ndigits[i]) ;

printf ( ",tabs = %d , new line = %d, spaces = %d , other = %d ",
tabs, white , new , nother );

return 0 ;
}
  1. 当我使用 GCC 编译它时只需按 Ctrl + z它打印

    数字 = 00000,制表符 = 4200912,新行 = 4194432,空格 = 2293540其他 = 2147307520

    这些数字从何而来?

  2. 我再次编译并输入 HELLO HELLO HELLO然后点击进入它打印 wtnwtnwnn

    • 为什么会这样(比预期有 3 n 个,为什么它算三个标签)?

最佳答案

您的一些case缺少break,这似乎不是您想要的。

此外,您还没有初始化 nothernewwhitetabs,但正在使用它们反正。这会导致未定义的行为。 (任何像样的编译器都会给你一个警告。)

关于c - 计算空格和制表符程序的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com