3 ms·
ok. a small challenge - read character input of undefined length, and then print the input out backwards. i guarantee the c++ code will be easier to write and u
by zabzonk 4y ago
ok. a small challenge - read character input of undefined length, and then print the input out backwards. i guarantee the c++ code will be easier to write and understand than any c code.
- camel-cdr 4y agoThat actually sounds like a fun way to explore different programming languages. Especially if you extend it to inputs that may take up more memory then you've got on your computer (let's say 100GB) and at least reasonably fast. I suppose it'd kinda trivial if you read the input from a regular (seekable) file, but if you actually read the 100 GB from stdin then this could get quite complex.
- zabzonk 4y agofinding good teaching examples is hard - here's one i prepared earlier https://latedev.wordpress.com/2011/07/28/writing-a-real-c-program-part-1a/ https://latedev.wordpress.com/2011/07/28/writing-a-real-c-pr... but could not complete as i was struck down with terrible depression, and then my mum & dad needed looking after, and then...... perhaps i will start it up again, now it is just me, and not exactly happy, but not depressed.
- johndough 4y ago> i guarantee the c++ code will be easier to write and understand than any c code. That will depend on how you define "understand". For a superficial level of understanding, you might be right. But the C++ code will make use of many concepts that would take a while to explain, for example references, classes, inheritance, templates, operator overloading, STL, and probably a bunch of other things I forgot.
- erik_seaberg 4y agoThere are books explaining those things, and as a professional I can expect to amortize the effort over years of other projects.
- wizzwizz4 4y ago#include <stdio.h> #include <stdlib.h> int main() { size_t len = 0, cap = 0; char *buffer = NULL; int c; while ((c = getchar()) != EOF) { if (len >= cap) { cap = (cap << 1) + 1; { char *newbuf = realloc(buffer, cap); if (!newbuf) { fprintf(stderr, "Could not reallocate to %zu. Printing what I've got.", cap); break; } buffer = newbuf; } } buffer[len++] = (char)c; } while (len --> 0) { if (putchar(buffer[len]) == EOF) { fprintf(stderr, "Output failure."); return 1; } } free(buffer); return 0; } Most of the verbosity here is in correctly handling errors, something that isn't much easier to do in C++. (Be warned: I haven't tested this code.)
- zabzonk 4y agoor in c++, simply call getline? i haven't traced thru your code, but i would not be surprised if there were errors in it, having written similar stuff myself. compare with using std::string and std::getline - easy to use and battle-hardened.
- wizzwizz4 4y agoHow does getline handle the out-of-memory condition? How do I avoid leaking memory – is that handled by std::string's RAII destructor? To detect the end-of-file condition, there's something about a failbit, but I'm only four pages of documentation in, so I don't know what that is yet. What would the equivalent code look like in C++, handling EOF and OOM conditions appropriately?
- blackpill0w 4y agoprobably std::string would throw std::bad_alloc, and there is also the failbit flag which std::getline sets
- zabzonk 4y agoif memory is exhausted, then getline throws a bad_alloc exception. if end of fileis reached (which i am not sure your code deals with correctly) then getline returns a stream in a bad state. so something in outline like this (syntactically correct. std:: omitted for brevity, but probably not what you would really write): string input; try { if ( cin.getline ( input ) ) { // ok read input, do something with it } else { // some sort of predictable error - look at state of cin to diagnose EOF } } catch (...) { /// something terrible happened - as hard to recover as it would be in c }
- a1369209993 4y agoIt's unclear exactly what you mean by "backwards" (and some interpretations like "print UTF-8 characters in reverse order" are infamously literally impossible[0]), but here's a straightforward/naive version (bytes in each line): #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sysexits.h> #define die(E,...) ({ \ fprintf(stderr,__VA_ARGS__); \ exit(E); }) void reverse(char* a,size_t z) { for(; z>=2 ;a++,z-=2) { char t=*a; *a=a[z-1]; a[z-1]=t; } } int main(void) { size_t z=16,i=0; char *a=malloc(z), *p=0; for(;;) { for(;;) { ssize_t n = read(0,a+i,z-i); if(n<0) die(EX_IOERR,"input error: %m"); if(n+i==0) exit(0); if(n==0) die(EX_DATAERR,"error: %zu bytes of garbage at end of file",i); p = memchr(a,'\n', (i += n) ); if(p) break; if(i > z/2) { a = realloc(a, (z = z+z/2) ); if(!a) die(EX_OSERR,"realloc(%zu bytes): %m",z); } } while(p) { reverse(a,p-a); fwrite(a,p-a+1,1,stdout); memmove(a,p+1, (i -= p-a+1) ); p = memchr(a,'\n',i); } } } This produces: $ ./a.out cat tac warning: incompatible implicit declaration of built-in function noitcnuf ni-tliub fo noitaralced ticilpmi elbitapmocni :gninraw naïve resumé �muser ev�an > i guarantee the c++ code will be easier to write and understand than any c code. Put up or shut up, as the saying goes. At the very least it ought to be easy to abstract out some of the memory allocation and file handling to use C++ builtins, and I'd be interested to see what other improvements you can manage. Edit: 0: Exercise for the reader: consider the input "abXc", where 'X' is some as-yet-undefined codepoint that will, at some point in the future, be defined as either a combining diacritic, or a standalone character. If 'X' is a character, the output should be "cXba", but if it's a diacritic, the output should be "cbXa". The information about which (mutually-exclusive) output is correct does not exist yet.
- deleted 4y ago[deleted]