【问题标题】:Ending program when Newline is entered [closed]输入换行符时结束程序[关闭]
【发布时间】:2022-09-23 19:24:52
【问题描述】:

我希望了解当用户在命令行中没有输入任何内容时如何使程序从 while 循环中中断。只有当用户在命令行中输入元素时,程序才应该继续循环:

#include <stdio.h>
#include <ctype.h>

int main() {
    int ch;

while ((ch == getchar()) != \'\\n\')  // read one char:  quit?
    putchar(toupper(ch));        // upper-case character and print

return 123 ;                     // Unix: check with: echo $?
  • 可以使用fgets()char 的数组吗?还是仅限于getchar()
  • 基本新手提示: 1. 经常检查IO错误或EOF!在这种情况下,检查 getchar() 是否返回 EOF。 2.启用编译器警告,-Wall -Wextra for海合会, /W4 用于 MSVC。然后在您自己的代码中修复警告! 3. 使用{},即使你不需要,并且在你的代码上使用自动缩进或自动格式化/美化。

标签: c


【解决方案1】:

使用此代码,您不是分配ch 变量,而是检查它是否等于getchar() 返回的值。
这样你的while循环永不停止迭代, 因为(ch == getchar()) 总是0 (false) 和0 != '\n' ('\n' 值是10)。

你可能想要改变(ch == getchar())(ch = getchar()),因此您可以使用输入输入的值更新ch

我建议你打开你的编译器警告, 所以它会告诉你类似的东西并帮助你理解和修复它。我想您可能会发现以下线程非常有用:What compiler options are recommended for beginners learning C?

示例 gcc 带有标志 -Wall -Wextra (https://godbolt.org/z/n6vG6f7Gv):

<source>:7:26: warning: comparison of constant '10' with boolean expression is always true [-Wbool-compare]
    7 | while ((ch == getchar()) != '\n')  // read one char:  quit?
      |                          ^~
<source>:8:5: warning: 'ch' is used uninitialized [-Wuninitialized]
    8 |     putchar(toupper(ch));        // upper-case character and print
      |     ^~~~~~~~~~~~~~~~~~~~

此外,它是一个好的做法main函数的末尾到return 0,这表明程序正确结束,并最终使其返回其他内容以防出错。

【讨论】:

  • 还应该有一个关于使用ch uninitialized 的警告,这也应该表明没有分配给它。
  • 无论输入的第一条语句如何,这都会中断,但目的应该是“仅”在用户输入空行时才中断。
【解决方案2】:

您需要确保 '\n' 位于该行的第一个位置。使用fgets() 是一个更简单的解决方案,因为它返回整个以空结尾的读取行,末尾带有“\n”:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
  char line[256];
  size_t l;
  size_t i;

  while(fgets(line, sizeof(line), stdin)) {

    l = strlen(line);

    // '\n' is the last char in line[]

    // If empty line (only '\n')
    if (l == 1) {

      break;

    }

    for (i = 0; i < l; i ++) {
      putchar(toupper(line[i]));
    }

  }

  return 0;

}

处决示例:

$ ./readl
$ ./readl 
azerty is not qwerty
AZERTY IS NOT QWERTY
     word preceded by spaces
     WORD PRECEDED BY SPACES

【讨论】:

    【解决方案3】:

    存储ch 的最后一个值。
    如果ch 的最后一个值和ch 的当前值都是换行符,则跳出循环。
    例如:
    命令&lt;enter&gt;command&lt;enter&gt;&lt;enter&gt;
    连续的换行符表示一个空白命令。

    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        int ch = 0;
        int last = 0;
    
        while ( ( ch = getchar()) != EOF) { // get value for ch
            if ( last == '\n' && ch == '\n') { // both equal to newline
                break;
            }
            putchar ( toupper ( (unsigned char)ch)); // print letters as uppercase
            last = ch; // store last value of ch
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多