c/c++语言开发共享检查角色是否是空格

我在C中创建了一个荒谬简单的程序来搞乱getchar() 。 程序将打印输出的内容,直到您按Enter键,它将保证您的线路每个不超过80个字符。 为此,我保持已输入的字符数的运行计数。 一旦char计数达到70,遇到的下一个空格将导致换行。 如果在70-80之间没有遇到空格,则无论如何都会发生换行。 我意识到这是一个超级天真的实现,可以左右优化,但请记住,我只是搞乱:

 while ((c = getchar()) != 'n') { if (lineLengthCount < 70) { putchar(c); lineLengthCount++; } else if (lineLengthCount < 80 && (c == ' ')) { printf("%cn", c); lineLengthCount = 0; } else { printf("%cn", c); lineLengthCount = 0; } } 

问题是c == ' '条件似乎没有实际检查空间。 我得到这样的输出:

 fitter happier more productive comfortable not drinking too much regula r exercise at the gym three days a week getting on better with your ass ociate employee contemporaries at ease eating well no microwaved dinner 

我希望在遇到空格时会截断线条。 相反,无论在第70行之后输入什么字符,都会创建一个新行。 我错过了什么吗? 这真的意味着任何角色吗?

     while ((c = getchar()) != 'n') { if (lineLengthCount < 70) { putchar(c); lineLengthCount++; } else if (lineLengthCount < 80 && (c == ' ')) { printf("%cn", c); lineLengthCount = 0; } else if (lineLengthCount >= 80){ printf("%cn", c); lineLengthCount = 0; } else{ putchar(c); lineLengthCount++; } } 

    我认为这应该有效。 当少于80个字符但字符不是空格时,这应该阻止else执行。

    编辑:我现在意识到,如果lineLengthCount小于80但字符不是空格,它根本不会被打印,所以我在最后添加了另一个来修复它。

    这不会更简短,更简洁吗?

     while ((c = getchar()) != 'n') { putchar(c); if((c == ' ' && lineLengthCount >= 70) || lineLengthCount >= 80){ printf("n"); lineLengthCount = 0; } else ++lineLengthCount; } 

    您的条件有问题:如果lineLengthCount > 70但是下一个字符不是空格,则会lineLengthCount最后一个,打破行并重置计数器。

    如果你完全不确定发生了什么,我会建议将“if”条件分解为三个明确的检查:

     while ((c = getchar()) != 'n') { lineLengthCount++; if (lineLengthCount < 70) { putchar(c); } if (lineLengthCount < 80 && (c == ' ')) { printf("%cn", c); lineLengthCount = 0; } if (lineLengthCount == 80) { printf("%cn", c); lineLengthCount = 0; } } 

    如果你想看看发生了什么,在每个“if”中写一些调试输出,以便注意它何时被调用。

    一旦它工作,你明白为什么,你可以编辑它并结合“ifs”...

    使用”完全有效。 您还可以尝试使用C标准库函数isspace()来检查字符是否为空格。 此函数返回一个布尔表达式,如:

     char ch = '0'; if (isspace(ch)) //the char is a space... 

    通过’is space’,这个函数实际上意味着任何’空格’字符,因此包括’ n’或任何其他打印为空格的字符。

    您还可以使用十进制值32,这意味着与空格相同:

     if (ch==32) 

    但是为了便于阅读,我宁愿使用第一个版本!

      以上就是c/c++开发分享检查角色是否是空格相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560203.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐