【问题标题】:Is it possible to collect multiple inputs in one getche() function?是否可以在一个 getche() 函数中收集多个输入?
【发布时间】:2017-01-03 21:12:04
【问题描述】:

我正在计划一个函数,它接受用户的输入(4 个整数)并检查每个整数是否大于 1 且小于 6,我想要一些简单的东西,并认为如果函数 ' getche()'(我想使用这个特定的功能,因为我不希望用户在输入后键入“输入”键)可以得到四个整数在一个代码中。

我想避免这种情况(如果可能的话):

int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
num1 = getche();
num2 = getche(); ...

我在想这样的事情是否可行:

int num = 0;
num = getche(4)

谢谢。

【问题讨论】:

  • 试试吧。当您尝试过某事并遇到特定问题时再回来。如果有疑问,请阅读该功能的手册页/参考。它会准确地告诉你它接受哪些参数以及参数的含义(提示:getche 不带任何参数)。
  • 您需要包含一个 minimal reproducible example 来显示您已经尝试过的内容......但无论如何getche() 不是这样工作的。
  • 你不能用scanf吗? Example here
  • @BrandonIbbotson no:“我不希望用户键入‘回车’键”。
  • 那你是怎么得到你的意见的?也许这会有所帮助:Scanf on non-stdin input.

标签: c function winapi input


【解决方案1】:

您不能只使用具有适当条件的循环和 getch() 函数吗?结果可能会更容易。

 int l = 0;
 while (l < 4)
 {
   x = getch();
  // your conditions
 }

【讨论】:

  • 我试过了,但是当我尝试检查参数是否满足条件时,它变得更加混乱。
  • 然后创建一个 4 元素 bool 数组。每次 getch() 后检查读取参数是否正常。如果没问题,则使用“true”填充数组的适当 id,否则使用“false”。
  • 我不允许制作任何数组
【解决方案2】:

使用 do/while 循环获取仅接受 1 到 6 的数字。使用 while 循环将四个数字连接成一个整数。

#include <stdio.h>
#include <stdlib.h>
//#include <conio.h>

int main(void)
{
    int num = 0;
    int digit = 0;
    int each = 0;

    printf("Type a four digit number using only 1 through 6\n");
    while ( each < 4) {
        do {
            digit = getchar ( );
            //digit = getch ( );//getch does not echo the typed character
            if ( digit == EOF) {
                fprintf ( stderr, "EOF\n");
                return 1;
            }
        } while ( digit < '1' || digit > '6');//loop if character is NOT 1 to 6
        //putch ( digit);//echo the character
        each++;
        num *= 10;
        num += digit - '0';
    }
    printf("the number is %d\n", num);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2021-12-13
    • 2021-01-07
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    相关资源
    最近更新 更多