简体   繁体   中英

Any help please, I'm trying to convert this C++ code to C code, but I'm having problem with fflush() function

Any help please, I'm trying to convert this C++ code to C code, but I'm having problem with fflush() function, or if there is another code functions like this, please do share it.

    #include <iostream.h>
    #include <time.h>
    #include<dos.h>
    int main()
    {
        cout << "Loading";
        cout.flush();
        for (int j=0; j<2; ++j) {
            for (int i = 0; i < 3; i++) {
                cout << ".";
                cout.flush();
                sleep(1);
            }
            cout << "\b\b\b   \b\b\b";
        }
    
        return 0;
    }
//________________________________________________________________________

    #include <stdio.h>>
    #include <unistd.h>
    int main()
    {
       printf("Loading");
        fflush();
        for (int j=0; j<2; ++j){
            for (int i = 0; i < 3; i++) {
                printf(".");
                fflush();
                sleep(1);
            }
           printf("\b\b\b   \b\b\b");
        }
        return 0;
    }

fflush takes an argument - the stream it is supposed to flush. You'd need to use fflush(stdout) .

Another problem is that the C++ code is semantically wrong too. Rather than using cout or printf to stdout , for such diagnostic messages one would be using cerr / stderr , which should be unbuffered anyway. using that you wouldn't probably need the fflush . Ie

#include <stdio.h>
#include <unistd.h>


int main(void)
{
    fprintf(stderr, "Loading");
    for (int j=0; j<2; ++j){
        for (int i = 0; i < 3; i++) {
            fprintf(stderr, ".");
            sleep(1);
        }
        fprintf(stderr, "\b\b\b   \b\b\b");
    }
}

fflush needs file pointer as argument. This would flush the local buffer data(stored in primary memory - mostly dram) corresponding to the file into the actual file stored in the secondary storage. For your case use fflush(stdout)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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