简体   繁体   中英

In this code Why Write() doesn't work with Int?

I cannot understand why this code doesnt work. it works fine with printf but i cannot get it to work with write...

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

int ft_putchar(char a,char b,char c){
    write(1,&a,1);
    write(1,&b,1);
    write(1,&c,1);
    return(0);
}

int main()
{
 int x = 0;
 int y, z;

 while(x <= 9){
     y = x + 1;
     while(y <= 9){
         z = y + 1;
         while(z <= 9){
             ft_putchar(x,y,z);
             z++;
         }
         y++;
     }
     x++;
 }
    return 0;
}

there are no error outputs

You need to convert ASCII to its digit equivalent before writing.

example 5 = '5' +'0'

As of now you are writing the ASCII values to terminal.

int ft_putchar(char a,char b,char c){

    a += '0';
    b += '0';
    c += '0';

    write(1,&a,1);
    write(1,&b,1);
    write(1,&c,1);
    return(0);
}

i want to print them like this but in the end it should have nothing 578, 579, 589, 678, 679, 689, 789, instead of 789, it should be 789 im using c= ','; write(1,&c,1); c= ' '; write(1,&c,1); c= ','; write(1,&c,1); c= ' '; write(1,&c,1);

You need to pass the delimiter to ft_putchar function,

int ft_putchar(char a,char b,char c, char del){

    a += '0';
    b += '0';
    c += '0';
    write(1,&a,1);
    write(1,&b,1);
    write(1,&c,1);
    write(1,&del,1);
    return(0);
}

int main()
{
 int x = 0;
 int y, z;

 while(x <= 9){
     y = x + 1;
     while(y <= 9){
         z = y + 1;
         while(z <= 9){

            if (x == 7 && y == 8 && z == 9)
             ft_putchar(x,y,z, ' ');
            else
             ft_putchar(x,y,z, ',');
             z++;
         }
         y++;
     }
     x++;
 }
    return 0;
}

When you used printf , I am guessing you used:

printf("%d %d %d",a,b,c);

So you are explicitly telling the function to interpret the variables as numbers, and print those. When you use write, it assumes that what you are using is a char . This means this would be the same as:

printf("%c %c %c",a,b,c);

Try that - you will see you still get blanks. That is because you are not interpreting the variables as characters, and so converting the numbers 1..9 to their ASCII letter value. These are not normal characters and will appear blank.

This would be the same if you used char in main instead of int . Your best option to convert a normal integer to a the ASCII value that prints said integer is via the answer by Kiran,

myInt += '0'; //Only works for numbers than 0..9. You may has well have used char to save space.

since all ASCII characters for numbers are consecutive.

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