Find the answer to your Linux question:
Results 1 to 2 of 2
Hey Guys, This is my first post and it is a very basic one. I hope to be an active member of this community as I learn more about The ...
  1. #1
    Just Joined!
    Join Date
    Aug 2010
    Posts
    1

    Wrong Output for C Program

    Hey Guys,

    This is my first post and it is a very basic one. I hope to be an active member of this community as I learn more about The C programming language and Linux.

    Here is my problem:

    Using Text: The C Programming Language (2nd Ed.)

    I'm not getting the correct output when I compile this code. It is supposed to display the number for each nw, nl, and nc. When I feed the program the EOF (Ctrl + D), it only displays the amount of times I entered anything. (For Example, I enter "Hi", "Hello", " ", "TAB", "ENTER"; This will display 5). Below is the code (directly from the book), any help appreciated. Thanks

    Code:
    #include <stdio.h>
    
    #define IN 1 /*inside a word*/
    #define OUT 0 /*outside a word*/
    
    /*count lines, words, and characters in input*/
    
    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;
    }
    } //end while
    printf("%d %d %d \n", nl, nw, nc);
    }
    I apologize for the sloppy formatting when I pasted it.

    -xDaedalusx

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    Just tried the code and it works...
    Make mine Arch Linux

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...