getchar_unlocked in windows undeclared

2019-02-11 04:27发布

问题:

Here is my code. I am providing source in the question since it's not so big:

#include <stdio.h>

void scan(int* i)
{
    int t=0;
    char c;
    bool negative=false;
    c=getchar_unlocked();
    while(c<'0'&&c>'9')
    {
        if(c=='-')
            negative=true;
        c=getchar_unlocked();
    }
    while(c>'0'&&c<'9')
    {
        t=(t<<3)+(t<<1)+c-'0';
        c=getchar_unlocked();
    }
    if(negative)
        t=~(t-1); //negative
    *i=t;
}

int main(int argc, char const *argv[])
{
    int i;
    scan(&i);
    return 0;
}

I know that the function defined here as scan is faster than scanf and is very useful on programming competitions. But for some reason this code is not working on windows and is working on linux. What do I do to get it working on windows. I am using the g++ compiler of dev-c++.

回答1:

getchar_unlocked is not a C or C++ standard function and therefore it's no surprise that it doesn't work on Windows. It is a POSIX standard I think, but Windows compilers don't support all POSIX functions.

If you replaced getchar_unlocked with getchar, it would kind of work, although the algorithm doesn't seem quite right.

You could do this with conditional compilation, like this for instance

#ifdef _WINDOWS
// no getchar_unlocked on Windows so just call getchar
inline int getchar_unlocked() { return getchar(); }
#endif


回答2:

Windows have the equivalent, _getchar_nolock, it is Windows specific.

See this link:

https://msdn.microsoft.com/en-us/library/4y2e9z0c.aspx

So if you are happy with a non-threadsafe version and you want the best possible performance you could do something like this:

#ifdef WIN32
// no getchar_unlocked on Windows so call _getchar_nolock
inline int getchar_unlocked() { return _getchar_nolock(); }
#endif


回答3:

getchar_unlocked() is mainly used for competitive programming, however, if you want to use this elsewhere, just make sure, only 1 thread is using it at a time. Same applies to putchar_unlocked() function too. It is a POSIX equivalent so Windows compiler doesn't support it. However, you can use either of two-

1) Normal speed

int getchar_unlocked() { return getchar(); }
void putchar_unlocked(char _c) {return putchar(_c); }

2) Fast speed

int getchar_unlocked() { return _getchar_nolock(); }
void putchar_unlocked(char _c) { return _putchar_nolock(_c); }


标签: c++ scanf