Find the answer to your Linux question:
Results 1 to 3 of 3
This is my small script: ============================================ #include <stdio.h> main () { int num1, counter; while (num1>0) { printf ("\nEnter a number:"); scanf ("%d", &num1); for (counter=0; counter<num1; counter++) printf ("*"); ...
  1. #1
    Just Joined!
    Join Date
    Mar 2009
    Posts
    5

    c question

    This is my small script:
    ============================================
    #include <stdio.h>

    main ()
    {
    int num1, counter;

    while (num1>0) {
    printf ("\nEnter a number:");
    scanf ("%d", &num1);
    for (counter=0; counter<num1; counter++)
    printf ("*");
    }
    }



    What is the simplest way to implement a check on the input. Basically i need to ignore if input is not a number.....

    Thank you.

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    scanf returns the number of successfully matched tokens (integers in that case). In your case scanf should return either 0 or 1 or EOF.
    Debian GNU/Linux -- You know you want it.

  3. #3
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    you could try something like....

    Code:
    char ch[2];
    int x = 0;
    const int MULTI = 10;
    
    ch[1] = '\0';
    
    while ((ch[0] = fgetc(stdin)) != '\n')
    {
           if (isdigit(ch[0]))
           {
           x = (x * MULTI) + strtol(ch, NULL, MULTI);
           }
    }
    of coarse this depends on your definition of number...did you mean digit
    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
  •  
...