我有一个学校项目,在其中,我需要输入一个四位数的数字,然后立即继续进行,而无需输入任何内容。例如:“输入数字:1424”,然后它继续,您不能再输入数字了,因为不需要输入Enter键。我尝试过,scanf("%4d",&num);
但它等待Enter键。
还有一个限制是...我不能在该项目中使用字符串,因此所有解决方案都必须没有字符串。
组织输入而不输入按键的唯一途径是功能getch
和getche
从conio.h
首标,即我想是不是在C / C ++标准。因此POSIX标准名称是_getch
和_getche
。
使用该功能,您将读取字符-如果char
分别处理每个字符,则不是字符串。
更新:
我的解决方案是:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch; // to store an input - single char
int number = 0; // to make number from inputs
printf("Enter a number: ");
int digits_cnt = 0;
while (digits_cnt < 4)
{
ch = _getche();
if (isdigit(ch))
{
number *= 10; // add an order to number
number += ch - '0'; // add a decimal digit to number
digits_cnt++; // count this digit to stop loop
}
}
// just to check result
printf("\nThe number %d was entered.\n", number);
return 0;
}
我假设所有4位数字都应该变成一个数字,但是也许您需要对它们进行其他处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句