Mohammed Sahib
Mohammed Sahib

Reputation: 1

Improve multiple `write` in C

I am writing a loop where each time I have three numbers which I have to print out using write as only one. I have converted them into chars and wrote them, calling a write only for the comma. As you can see this is a really ugly piece of code, besides the fact that I get an even uglier comma at the end of all. Is there a better way of doing this without calling other functions?

char n1=p+'0';
char n2=s+'0';
char n3=t+'0';
write(1,&n1,1);
write(1,&n2,1);
write(1,&n3,1);
write(1,",",1);

Upvotes: 0

Views: 464

Answers (1)

paxdiablo
paxdiablo

Reputation: 881553

char n1=p+'0';
char n2=s+'0';
char n3=t+'0';

If only there were some way in C to have a group or an array of objects so that you could treat them in a common manner, using some form of index or pointer :-)

Levity aside, this screams out for an array-based solution, something like:

char buff[100];
buff[0] = p + '0';
buff[1] = s + '0';
buff[2] = t + '0';
buff[3] = ',';
write(1, buff, 4);

Or even, assuming they're guaranteed to be 0-9, which is pretty much a requirement of the original code:

char buff[100];
sprintf(buff, "%d%d%d,", p, s, t);
write(1, buff, 4);

Upvotes: 2

Related Questions