简体   繁体   English

如何控制输入数据格式(C)?

[英]how to control input data format (C)?

anyone knows an efficient way to check out the format of an scanf'ed data? 有谁知道一种有效的方法来检查扫描数据的格式?

eg if I try to read an integer and I type a character, how would you do to tell the program that is not correct? 例如,如果我尝试读取一个整数并输入一个字符,您将如何告诉该程序不正确?

You can check if scanf() succeeds, it returns the number of successful conversions it performed. 您可以检查scanf()成功,它返回执行的成功转换次数。

You should always check this, before relying on the result since if it failed the variable(s) might contain undefined data leading to undefined results if referenced. 在依赖结果之前,您应始终进行检查,因为如果失败,则变量可能包含未定义的数据(如果被引用则导致未定义的结果)。

You can use if to check, and re-try with a different conversion specifier on failure: 您可以使用if检查,并在失败时使用其他转换说明重试:

if(scanf("%d", &x) == 1)
  printf("got integer %d\n", x);
else if(scanf("%c", &y) == 1)
  printf("got character '%c'\n", y);
else /* more attempts */

Of course it can become troublesome if there are "sub-matches", so the order can matter. 当然,如果存在“子匹配项”,则会变得很麻烦,因此顺序很重要。 It's also way better to split the input processing into two steps for the above: 这也是更好的方式来输入处理分为两个步骤,以上:

  1. Read a full line of input using fgets() 使用fgets()读取整行输入
  2. Use sscanf() to parse the line 使用sscanf()解析行

That way you avoid problems due to the input being streamed in: 这样,您可以避免由于输入流而导致的问题:

char line[128];

if(fgets(line, sizeof line, stdin) != NULL)
{
  int x;
  char y;

  if(sscanf(line, "%d", &x) == 1)
    printf("got integer %d\n", x);
  else if(sscanf(line, "%c", &y) == 1)
    printf("got character '%c'\n", y);
}

Note that if you wanted to scan for both an integer and a float, it can still become troublesome since a typical float (such as "3.1416" ) begins with what is a legal integer. 请注意,如果要同时扫描整数和浮点数,由于典型的浮点数(例如"3.1416" )以合法的整数开头,因此它仍然很麻烦。 For those cases you can use the strtoXXX() family of functions, which let you check the remainder after doing the conversion. 对于这些情况,您可以使用strtoXXX()函数系列,该函数系列让您在转换后检查其余部分。

As you have mentioned in the question that you are playing with numbers and chars only there is a very simple solution as follows 正如您在问题中提到的那样,您只在玩数字和字符,这是一个非常简单的解决方案,如下所示

//while reading a char
scanf("%c",&temp);
if(!((temp >=  65 && temp <= 90) || (temp >= 97 && temp <= 122)))
printf("Only characters are allowed!\n");

hope this helps! 希望这可以帮助!

scanf("%s", &c);
if(!atoi(c)) puts("You have entered a character");
if(atoi(c) != 0) puts("You have entered an integer");
Scanner sc = new Scanner (System.in);

try {

       // assume that the input from the user is not an integer, 
       // in that case the program cannot convert the input (which is a String) into
       // an integer. Because of this situation it'll jump to the 'catch' part of the 
       // program and execute the code. 

       int input = Integer.valueOf(sc.nextInt);

       // if the input is an integer lines below the above code will be executed. 


       // Ex. "int x = ( input + 10 ) "


}

catch (Exception ex) {

        System.out.println("Invalid input, please retry!");

        // if you want to get more information about 
        // the error use the 'ex' object as follows.

        System.out.println(ex);


}

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

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