-3

I read in geeksforgeeks and added the template to it so that it can work for every integer data types such as long, long long and int.

#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;
}

But when I tried executing it, the output is shown as 0 and not the input number. Is the above code wrong?

JeJo
  • 30,635
  • 6
  • 49
  • 88
Nick
  • 9
  • 2
  • 1
    Unrelated: [What is a magic number, and why is it bad?](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) – user4581301 Jun 30 '19 at 06:01
  • 1
    Notice that `` is *not* a [standard C++ header](https://en.cppreference.com/w/cpp/header) (just an ugly implementation detail). So don't use it. Also, read [*How to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Basile Starynkevitch Jun 30 '19 at 06:07
  • Please get a [good C++ book](https://stackoverflow.com/a/388282/) and start reading if you want to learn C++ systematically. – L. F. Jun 30 '19 at 09:41

1 Answers1

4

the output is shown as 0 and not the input number.

the test in

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

is not the right one and must be

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

Because of the error when you enter for instance 123 none of the for do something and x stay equals to 0.

After the correction, compilation and execution (also adding <<endl in the cout):

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 $ 

Out of that to use the codes is not readable nor portable, better to do

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

and these for are more readable being while.

As signaled by @Basile Starynkevitch you can also use std::isdigit to check if c is a digit or not, you would not have had your mistake using it.

Warning, if you reach EOF in the first for the code loops without ending, it is more secure to add && (c != EOF) in it and for that to type c with int rather than char.

I also encourage you to no use #include <bits/stdc++.h>, see Why should I not #include <bits/stdc++.h>?

bruno
  • 32,421
  • 7
  • 25
  • 37