Ouch !
Ouch !
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Is it really that easy as everyone assumes?
I have been stuck on this exercise since sunday , I have spent hours but I can't get to the solution
the output should be 1: inputCode:#include <stdio.h> int main() { int c; int counter=1; while((c=getchar())!=EOF){ putchar(c); if ( c == '\n' ) { putchar(counter+'0'); putchar(':'); putchar(' '); ++counter; } } return 0; }
what am I doing wrong?
I'd expect the first 9 lines to be ok.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I apologize. I didn't realize he was only allowed to use putchar and that Salem had mentioned something about that previously. Of course, you could just do it like this:
And don't use 48 when you mean '0'! (Why do beginners constantly do that???)Code:putchar(line / 10); putchar(line % 10);
A little inaccuracy saves tons of explanation. - H.H. Munro
Althouh it does more clearly show your intention, the reason is deeper. To be portable you can't assme ascii (or utf-8). '0' will always be the correct value, no matter what character set. (In EBCDIC the value of '0' is 240.)
character encodings
EDIT: I forgot to add '0' on the putchar in that little code snippet I posted above. (How embarrassing!) It should be:
Code:putchar(line / 10 + '0'); putchar(line % 10 + '0');
Last edited by john.c; 05-08-2018 at 01:50 PM.
A little inaccuracy saves tons of explanation. - H.H. Munro
I don't see how you are going to get the line numbers in front of the lines any other way.
If your tutor has a sense of humor, you can try this ...
Code:while((c=getchar())!=EOF) if ( c == '\n' ) { {do the coversion of line number -> ascii here} putchar(':'); putchar(' '); ++linenum; }
Last edited by joemccarr; 05-08-2018 at 02:53 PM. Reason: non closed quote
hi
I want to thank you all for your help
I have finally solved the problem
It was difficult though and yes I am a beginner