I'm creating an absurdly simple program in C to mess around with getchar()
. The program will print out what you input until you press enter and it will guarantee that your lines are no more than 80 chars each. To do this, I keep a running count of how many characters have been entered. Once the char count hits 70, the next space encountered will cause a line break. If no space is encountered between 70-80, a line break will occur regardless. I realize this is a super naive implementation and could be optimized left and right, but remember, I'm just messing around:
while ((c = getchar()) != '\n') {
if (lineLengthCount < 70) {
putchar(c);
lineLengthCount++;
}
else if (lineLengthCount < 80 && (c == ' ')) {
printf("%c\n", c);
lineLengthCount = 0;
}
else {
printf("%c\n", c);
lineLengthCount = 0;
}
}
The problem is the c == ' '
conditional doesn't seem to be actually checking for a space. I get output like this:
fitter happier more productive comfortable not drinking too much regula
r exercise at the gym three days a week getting on better with your ass
ociate employee contemporaries at ease eating well no microwaved dinner
where I was hoping that the lines would be truncated when a space was encountered. Instead, no matter what character is entered after line 70, a new line is created. am I missing something? Does ' '
really mean any character?
while ((c = getchar()) != '\n') {
if (lineLengthCount < 70) {
putchar(c);
lineLengthCount++;
}
else if (lineLengthCount < 80 && (c == ' ')) {
printf("%c\n", c);
lineLengthCount = 0;
}
else if (lineLengthCount >= 80){
printf("%c\n", c);
lineLengthCount = 0;
}
else{
putchar(c);
lineLengthCount++;
}
}
I think this should work. That should prevent the else from executing when there are less than 80 characters but the character isn't a space.
EDIT: I realized now that instead if lineLengthCount is less than 80 but the character isn't a space it wouldn't get printed at all, so I added another else at the end to fix it.
Wouldn't this be shorter and more concise?
while ((c = getchar()) != '\n') {
putchar(c);
if((c == ' ' && lineLengthCount >= 70) || lineLengthCount >= 80){
printf("\n");
lineLengthCount = 0;
}
else
++lineLengthCount;
}
There's a problem with your conditions: if lineLengthCount
is > 70 but the next character is not a space, the last else
will be hit, breaking line and resetting the counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With