繁体   English   中英

如何在 C 中按 Enter 键终止程序?

[英]How Terminate the Program on Pressing Enter key in C?

我正在制作一个小项目,我必须将不同的值转换为不同的基数,如 10、8、16。等待输入而不是简单地终止。 我在在线编译器上使用 C11 版本的 C。 这是我的代码。

#include "ConvertInBackgnd"

#include<stdio.h>

int main() {
  int choice;
  printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
  l1: printf("Input your choice : ");
  scanf("%d", &choice);
  switch (choice) {
  case 1:
    dec_bin();
    break;
  case 2:
    bin_dec();
    break;
  case 3:
    dec_octal();
    break;
  case 4:
    octal_dec();
    break;
  case 5:
    dec_hex();
    break;
  case 6:
    goto l1;
  default:
    printf("Invalid choice.");
    break;
  }
  printf("Input 6 for reconverting the values.");
  scanf("%d", &choice);
  if (choice == 6) {
    goto l1;
  } else
    return 0;
  return 0;
}

我制作了一个单独的文件,我在其中制作了函数,我认为没有必要也把代码放在这里。

考虑使用fgets将输入输入到字符数组中。
如果需要,可以使用sscanfstrtol或其他方法解析输入。

#include<stdio.h>

int main() {
    char line[100] = "";
    do {
        printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
        printf("Input your choice : ");
        fgets ( line, sizeof line, stdin);
        switch ( line[0]) {
            case '1':
                printf ( "dec_bin()\n");
                break;
            case '2':
                printf ( "bin_dec()\n");
                break;
            case '3':
                printf ( "dec_octal()\n");
                break;
            case '4':
                printf ( "octal_dec()\n");
                break;
            case '5':
                printf ( "dec_hex()\n");
                break;
            case '6':
            case '\n':
                break;
            default:
                printf("Invalid choice.");
                break;
        }
        if ( line[0] != '\n') {
            printf("Input 6 for reconverting the values.");
            fgets ( line, sizeof line, stdin);
        }
    } while ( line[0] == '6');
    return 0;
}

解决输入问题:

scanf("%d", &choice)

现在您正在获取 int 值,尝试使用 char 值并将输入键与其匹配。 然后你就可以做你想做的事情了。

好的,所以如果按下 Enter 键,我想终止程序。 所以我首先是一个新手,然后我意识到这没什么大不了的,为此我只需要将一个char作为输入,然后检查该char输入是否为输入键。 它是按回车键后终止程序的示例代码。

 char line;

 scanf("%c",&line);

    if(line=='\n')
       return 0;
    else
    // your other code

但是如果你的程序不接受输入,那么你应该在上面提供的代码之前通过在上面的代码之前添加这一行来清除缓冲区。

 while(getchar()!='\n');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM