首页 > 解决方案 > 这个函数做了什么来帮助它以不同的方式接受输入以及 for 循环中的条件是如何执行的

问题描述

这个函数做了什么来帮助它以不同的方式接受输入,以及 for 循环中的条件是如何执行的?

void scanint(int &x)
{
  int flag=0;
  register int c = gc();
  if(c == '-') flag=1;
  x = 0;
  for(;(c<48 || c>57);c = gc());//why is this used?
  for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}//how  is this executed ?
  if(flag == 1)x=-x;
}

标签: cfunctionfor-loop

解决方案


这不是c。

void scanint(int &x) {/* Whatever */}
//               ^^

这定义了一个接受对 an的引用int的函数,并且在 c 中没有引用,参数按值传递给函数。您当然可以使用指向 的指针int但是应该相应地更改函数的主体,*x使用x.

以下假设gc()代表类似于 的函数getchar(),因此发布的代码是从中提取值的一种非常糟糕的方式:intstdin

void scanint(int &x)   // Or 'int *x' in C
{
    int c = gc();      // register was deprecated in C++17

    bool is_negative = (c == '-'); // C has bool from C99 too

    x = 0;             // '*x = 0;' in C. The same applies to the following code

    // Considering only ASCII, ignores non-digit characters
    // E.g. from "  123" it ignores the first two spaces,
    // but, given " -123", it will ignore the sign too. Bad, as I said.
    for( ;
         ( c < '0'  ||  c > '9');  
         c = gc() )
    ;

    // Now computes the actual number using an old trick that should
    // be left to the compiler to be exploited:
    // 10 * x = (2 + 8) * x = 2 * x + 8 * x = x << 1  +  x << 3 (bit shifts)
    for( ;
         '0' <= c  &&  c <= '9';
         c = gc() )
    {
        x = (x << 1) + (x << 3) + c - '0';
    }
    if ( is_negative )
        x = -x;
}

推荐阅读