Thread: Cprogramming Assignment, having problems.

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    3

    Cprogramming Assignment, having problems.

    The assignment: Write a program to do the following. When the program starts, you start type characters from the keyboard. The program should print out a warning if you type any characters that are not digits, i.e., from '0' to '9'. In addition, when you stop the typing (by typing a non-character), your program will print out the number of digits and number of non-digit characters you have typed.

    Code:
    #include <stdio.h>
    #include <cstdlib>
    
    
    int main() {
        int digit = 0;
        int nondigit = 0;
        int c;
    
        while((c=getchar()) != EOF)
        {
          if(c>='0'&&c<='9')
    	                digit++;
          else
            {  
    	printf("ERROR:NOT A DIGIT\n");
                                nondigit++;
    	}
        }
        printf("%d\n", digit);
        printf("%d\n", nondigit);
    
        system("pause");  
        return 0;
    }
    My code recieves input from the keyboard and prints out the correct output when a non-character is typed, but I can't seem to get it to print the error message after a non-digit is input without hitting enter.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Just for fun, add a second c=getchar(), before the if() statement.

    Why does it work like that? Does the second getchar() pull out the newline remaining in the keyboard buffer?

    (hint: a newline has an ascii value of 10)

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Try flushing stdout.
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  2. Need help with Code! Having problems.
    By Invertalon in forum C Programming
    Replies: 4
    Last Post: 03-05-2008, 06:17 AM
  3. Big problems with assignment, please help!!
    By JFonseka in forum C Programming
    Replies: 12
    Last Post: 03-25-2007, 12:16 AM
  4. C Pointers Problems
    By mhelal in forum C Programming
    Replies: 8
    Last Post: 01-10-2007, 06:35 AM
  5. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM