为什么使用快速扫描功能时无法获得期望的输出?

时间:2019-06-30 05:33:43

标签: c++ algorithm templates

我读了geeksforgeeks并将其添加到模板中,以便它可以适用于longlong longint等每种整数数据类型。

#include <bits/stdc++.h>
using namespace std;

template<typename T>
void fs(T& x)     // For faster scanning of input
{  
    int n = 1;
    char c = getchar();
    x = 0;
    for (; (c < 48 || c>57) && c != '-'; c = getchar());
    if (c == '-') {
        n = -1;
        c = getchar();
    }
    for (; (c < 47 && c < 58); c = getchar())
        x = (x << 1) + (x << 3) + c - 48;
    x = n * x;
}

int main() 
{
    int test;
    fs(test);
    cout << test;
    return 0;
}

但是当我尝试执行它时,输出显示为0,而不是输入数字。上面的代码错误吗?

1 个答案:

答案 0 :(得分:4)

  

输出显示为0,而不是输入数字。

测试

for (;(c<47 && c<58);c=getchar())

不是正确的,必须是

for (;(c>47 && c<58);c=getchar())
//      ^

由于输入错误123时, for 都不做任何事情,并且 x 保持等于0

更正,编译和执行后(还在 cout 中添加<<endl):

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra cc.cc
pi@raspberrypi:/tmp $ ./a.out
123
123
pi@raspberrypi:/tmp $ ./a.out
-123
-123
pi@raspberrypi:/tmp $ 

使用这些代码既不可读也不便于携带,最好这样做

for(;(c<'0' || c>'9') && c!='-';c=getchar()); 
...
for (;(c>='0' && c<='9');c=getchar())

和这些 for 时更具可读性。

根据@Basile Starynkevitch的信号,您还可以使用 std::isdigit 来检查 c 是否为数字,使用不会出错它。

警告,如果在代码的第一个 for 中到达EOF而没有结束,则在其中添加&& (c != EOF)并键入 c 更为安全。 em>和 int 而不是 char

我也鼓励您不要使用#include <bits/stdc++.h>,请参阅Why should I not #include <bits/stdc++.h>?