Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

printf() prints only the first character

Recently I came across an example from the book "The C Programming Language" and decided to run it:

#include <stdio.h>

#define IN 1
#define OUT 0

int main() {

    int c, nl, nw, nc, state; 

    state = OUT; 
    nl = nw = nc = 0; 
    while ((c = getchar()) != EOF) {
        ++nc; 
        if (c == '\n') 
            ++nl;
        if (c == ' ' || c == '\n' || c == '\t') 
            state = OUT;
        else if (state == OUT) {
            state = IN; 
            ++nw;
        } 
    }
    printf("%d %d %d\n", nl, nw, nc);
}

There is a problem related to printf(). For some reason, only the first character is printed, although there should be 3 of them. What could be the problem?

System – Windows. For editing code I use Visual Studio Code. Compiler – gcc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Interesting fact: on macOS this problem do not occur and the output is as needed.

Input:

a       
ab 
abc
abcd

Output:

4

Desired output:

4 4 14

Thanks in advance!

ANSWER:

I used control-C thinking that it was suitable as an EOF-indicator. The correct option is to use control-Z.

>Solution :

The idea here is:

  • to count letters, words and lines from the input file. Words are separated by spaces or tabs or newlines.
  • the program implements a minimalist FSM, a finite state machine with 2 states.

I am not sure I understand the question, but here is the output for this file

one another
one
another
3 4 24

And it seems ok. Note that is you are testing this interactively control-Z is the EOF indicator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading