Maddie Elizabeth Maddie Elizabeth - 2 months ago 11
C Question

read in input, then read in each char in c programming

I am working on a practice problem from my textbook by kernigan and ritchie (again for practice, not for credit).

The problem states to write a program that prints a histogram of the lengths of words in its input.

I want to do this by printing a "_" for every char that I read. However, I'm having a lot of trouble reading chars.

Right now, my program looks like this:

int main(){

int c;
char str[100];
scanf("%s", str);
printf("|");
while((c = getchar()) != EOF){
putchar(c);
printf("_");
}

printf("|");
return 0;


}

main compiles. However When I try to use it and give it a word (of any length), it simply prints:
|
_

and then the cursor moves right next to the underscore. What am I doing wrong? Why is the underscore printed after the "|" rather than next to it, as I didn't use \n ?

Answer

The output you see is because the scanf("%s", str) line captures the word you input up to the default delimiter character which is space and then goes on to print '|' character then attempts to read more from stdin.

If you had entered say mylong word do you like it? then ctrl-z

You would see:

| _w_o_r_d_ _d_o_ _y_o_u_ _l_i_k_e_ _i_t_?_ _^Z |

This is because the characters word do you like it? are still in the stream to be processed.

If you only enter a single word without spaces then you will see what you observed.

The two lines:

char str[100];
scanf("%s", str);

could be removed and then you won't be capturing the word and doing nothing with it.

Alternatively, if you want to use scanf you could change like this:

#include <stdio.h>

int main(){
    char str[100];
    char* p = str;
    scanf("%s", str);
    printf("|");
    while (*p != NULL) {
        putchar(*p++);
        printf("_");
    }
    printf("|");
    return 0;
}

This code prints each character in str, interspersing with the _ character.