简体   繁体   English

getchar_unlocked()解释

[英]getchar_unlocked() explanation

In this snippet, why is the condition checking whether ch<'0' || 在此代码段中,为什么要检查ch <'0'||的条件? ch > '9' necessary.Why can't only the if statement suffice? ch>'9'是必需的。为什么仅if语句不能满足要求?

   #define getcx getchar_unlocked 
 inline void inp( int &n )
  n=0;
  char ch=getcx();
  int sign=1;

 while( ch < '0' || ch > '9' ) // Why is this while loop essential?
  {if(ch=='-')sign=-1; ch=getcx();}

  while(  ch >= '0' && ch <= '9' )
       n = (n<<3)+(n<<1) + ch-'0', ch=getcx();
  n=n*sign;
  }

Function returns 3454 as 3454 and -3454 as -3454 函数将3454作为3454返回,将-3454作为-3454返回

The idea behind the while loop is to skip over all non-digit characters on the way to the first digit, paying attention only to dashes. while循环背后的想法是跳过到第一位数字的所有非数字字符,只注意破折号。 For example, this code would interpret 例如,此代码将解释

hello-world123

as -123 作为-123

A more likely scenario, though, is that the author of this code fragment wanted to skip over spaces. 不过,更可能的情况是该代码片段的作者希望跳过空格。 This kind of code is common in programming competitions, where programmers use the less safe getchar_unlocked in order to squeeze out a few microseconds while reading the input. 这种代码在编程竞赛中很常见,在编程竞赛中,程序员使用不太安全的getchar_unlocked以便在读取输入时挤出几微秒的时间。

It is needless to say that this is a very quick and dirty parser, intended for use with extremely clean data. 不用说,这是一个非常快速且肮脏的解析器,旨在用于极其干净的数据。

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

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