Reputation:
right now I am writing a program on C language based on the task 1.12 from Brian and Ritchie book. The program has to output the input stream one word per line. Here is the code:
#include <stdio.h>
int main(){
int ct;
while((ct = getchar()) != EOF){
if(ct == ' '){
ct = ct - ' ';
putchar(ct);
printf("\n");
}else if(ct == '\n'){
ct = ct - '\n';
putchar(ct);
printf("\n");
}
}
}
It seems to work, but it only outputs blank lines when I enter the input. Where did I mess up?
Upvotes: 0
Views: 199
Reputation: 3855
In your code, you have the two cases where you check if ct
is either a space (' '
) or a newline character ('\n'
), and these are the only places where you are printing out the character, using putchar
. Your code isn't ever printing anything out outside of these two cases, so you need to add a case to handle regular characters and to print those out as well. Something like:
#include <stdio.h>
int main(){
int ct;
while((ct = getchar()) != EOF){
if(ct == ' '){
ct = ct - ' ';
putchar(ct);
printf("\n");
}else if(ct == '\n'){
ct = ct - '\n';
putchar(ct);
printf("\n");
} else {
putchar(ct)
}
}
Also, while putchar
does take an int
as an argument, you do not need to manually convert it using ct - ' '
, for example. You can pass the ct
char
directly to putchar
and it will print it out accordingly
Upvotes: 1