Jump to content

Just a little code problem...


OtterFox

Recommended Posts

Whenever I run this code the while ((c = getchar()) != EOF) wont end and It keeps asking for more input, I've tried with microsoft visual C++, cygwin+gcc and Linux.

#include <stdio.h>
int main()
{
    int c, i, nwhite, nother;
    int ndigit[10];

    nwhite = nother = 0;
    for(i = 0; i < 10; ++i) {
        ndigit[i] = 0;
    }
    
    while ((c = getchar()) != EOF) {
        if(c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if(c == ' '|| c == 'n' || c == 't')
            ++nwhite;
        else
            ++nother;
    }

    printf("digits =");
    for(i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %dn", nwhite, nother);

    return 0;
}

if I change it to...

...    
    while ((c = getchar()) != EOF) {
        if(c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if(c == ' '|| c == 'n' || c == 't')
            ++nwhite;
        else
            ++nother;
    
        printf("digits =");
    for(i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %dn", nwhite, nother);

    }

    
    return 0;
}

It prints the correct output but it also prints it for each loop which is understandable.

How do I make it so than when I press enter it returns a EOF?

Thanks

Link to comment
Share on other sites

How do I make it so than when I press enter it returns a EOF?

Well, you could of course test to see if c now holds the Enter key (well, keys. Enter is chars 10 immediately followed by 13 on Windows, only char 10 on UNIX and only char 13 on Mac IIRC). Ctrl-D I think is what makes getchar return an EOF when it's reading from the keyboard.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...