4 ms·
You could check for ferror when getchar returns EOF. Otherwise very nice. I wrote almost exactly the same code before I saw yours. The only difference was that
by johndough 4y ago
You could check for ferror when getchar returns EOF. Otherwise very nice. I wrote almost exactly the same code before I saw yours. The only difference was that I used multiplication by 2 instead of left shift since the goal was easier understanding. gcc can perform this optimization (for unsigned integers).
I also looked up whether the cast from int to char is safe. Seems that it is not, but probably fine in practice https://stackoverflow.com/questions/19250521/best-way-to-portably-assign-the-result-of-fgetc-to-a-char-in-c https://stackoverflow.com/questions/19250521/best-way-to-por...
Of course all bets are off when someone tries to reverse emoji soup with this, but I am not knowledgeable enough about this topic to claim whether a general solution is even possible.
- wizzwizz4 4y ago> but I am not knowledgeable enough about this topic to claim whether a general solution is even possible. The correct way to reverse a Unicode string is to blit it back to front. Addendum: a real C programmer helped me write (i.e., wrote most of) the following program: #include <skalibs/skalibs.h> int main() { stralloc sa = STRALLOC_ZERO; slurp(&sa, 0); stralloc_reverse(&sa); if (allwrite(1, sa.s, sa.len) < sa.len) { strerror_diefusys(1, "output everything"); } } In the event of an allocation failure, this program will output nothing; other than that, it's the same as my C program above. Perhaps the problem isn't C, but its standard library?
- steveklabnik 4y ago> Perhaps the problem isn't C, but its standard library? That's certainly at least a factor. In Rust, the "reverse a string byte by byte" bit could look like: let reversed_string = String::from_utf8(some_string.bytes().rev().collect::<Vec<u8>>())?; This is just what I thought of first. Peeking at the standard library examples, this one is fun: unsafe { let vec = some_string.as_mut_vec(); vec.reverse(); } This is unsafe because you may create invalid utf8, but we've already established that's not something we care about, so... But yeah stuff like this isn't impossible in C, though you'd not have method call syntax, of course. Rust's libraries are just richer here.