简体   繁体   中英

Printf to Fprintf

I want to create a file with sql commands :

CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100));
INSERT INTO t1 VALUES(1,13153,'thirteen thousand one hundred fifty three');
INSERT INTO t1 VALUES(2,75560,'seventy five thousand five hundred sixty');
... 995 lines omitted
INSERT INTO t1 VALUES(998,66289,'sixty six thousand two hundred eighty nine');
INSERT INTO t1 VALUES(999,24322,'twenty four thousand three hundred twenty two');
INSERT INTO t1 VALUES(1000,94142,'ninety four thousand one hundred forty two');

It works when I use printf :

printf("INSERT INTO t1 VALUES(%d, %d, '", i, nbAlea);
NombreVersMots(nbAlea);
printf("');\n");

But I can't use fprintf :

fprintf(fichier, "INSERT INTO t1 VALUES(%d, %d, '", i, nbAlea);
fprintf(fichier, NombreVersMots(nbAlea)); // <- HERE IS MY PROBLEM
fprintf(fichier, "');\n");

I don't find a way to use the second line.

I give you the procedures of you need them :

char *one[]={"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
char *ten[]={"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
void pw(long n,char ch[])
{
    if(n>19)
    {
        printf("%s %s ",ten[n/10],one[n%10]);
    }
    else
    {
        if(n) // pour eviter les espaces inutiles quand la boucle n'affiche rien
        {
            printf("%s ",one[n]);
        }
    }
    if(n)
    {
        printf("%s",ch); // affiche 'million', 'thousand' ou 'hundred'
    }
}

void NombreVersMots(long m)
{
    pw((m/1000000),     "million ");
    pw(((m/100000)%10), "hundred ");
    pw(((m/1000)%100),  "thousand ");
    pw(((m/100)%10),    "hundred ");
    pw(((m/1)%100),     "");
}

Thanks a lot if you can help me !

Your call to NombreVersMots calls pw which calls printf (not fprintf ). You could fix this by replacing printf in pw with fprintf and having NombreVersMots and pw take a FILE* argument which is passed down to fprintf .

Rewrite NombreVersMots to use fprintf() , and to accept a FILE * argument. Then, if you want to use printf at the top-level, call it using stdout as the argument. ie:

void pw(FILE *file, long n, char ch[])
{
   ...
   fprintf(file, "blah");
}

void NombreVersMots(FILE *file, long m)
{
    pw(file, (m/10000000), "million);
}

NombreVersMots(fichier, 42);  // As before
NombreVersMots(stdout, 43);  // To stdout

well problem is that internally NombreVersMots(long m) uses printf and not fprintf . Consider modifying it ( in particular the pw function ) to use fprintf internally too, maybe adding the output stream as a parameter to NombreVersMots(long m) as well.

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