Thread: Another "integer only" problem

  1. #1
    Registered User
    Join Date
    Jan 2004
    Posts
    49

    Another "integer only" problem

    Hi and Happy New Years to all.

    This is yet another question about writing a program that accepts only integers as valid input. The basics are the same as other posters: read in the users input, if it is not an integer, loop a request for input until it is an integer.
    I think I have the logic figured out on how to do it (thanks Hammer for the informative FAQ), but I am stuck on a problem getting the entire user input evaluated.
    Currently my program only detects an invalid input when the input is in the format of ##X, where # is a digit, and X is alpha.
    If e45 is entered, it likes it. If 4e5 is entered, that it likes too.
    It will only fail if 45e is entered, or anytime the last character is not a digit, but only the last character.
    I would like to figure out what is stopping it from reading the rest of the input.
    The section of code that I really feel is to blame is the following:

    [CODE]

    length = strlen(line);

    for (i = 0; i < length; ++i)
    {
    if (line[i] == '\n')
    {
    }
    else
    {
    error = 0;
    if ( isdigit (line[i] ))
    [END CODE]

    However, I don't have enough experience to troubleshoot this witout some guidance. I can tell what I think is happening- it is reading the last character input by the user, and if it is a digit, it is happy and doesn't look any further. Why it is not looking any further and evaluating the rest of the input is my concern.
    Here is the entire code, I hope someone can enlighten me.

    [CODE]

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>

    #define MAXLINE 100

    int main(void)
    {
    char line[MAXLINE];
    int n;
    int i;
    int length;
    int error = 0;


    do {
    printf(" Enter a positive integer: \n");
    printf("\n");
    fgets(line, MAXLINE, stdin);

    sscanf(line, "%d", &n);
    length = 0;
    length = strlen(line);

    for (i = 0; i < length; ++i)
    {
    if (line[i] == '\n')
    {
    }
    else
    {
    error = 0;
    if(isdigit(line[i]))
    {
    }
    else
    {
    error = 1;
    }
    }
    }
    if (error)
    {
    printf("\n Try again!");
    }
    else
    {
    printf("\n Looks like an integer to me. Thanks!\n");
    }
    } while (error);
    return 0;
    }
    [END CODE]

    RedZippo
    Semper Fi!

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    A program that accepts only integers
    Code:
    #include <stdio.h>
    
    int main(void){
         int x;
         printf("Enter a number:  ");
         fflush(stdout);
         if((scanf("%d",&x))!=1){
             printf("You didn't enter a digit\n");
             return 1;
         }
         else{
              printf("You entered a digit\n");
         }
         return 0;
    }
    scanf, sscanf and all the others return the number of variables assigned. It may improperly assign it if you enter an alpha but if you error-check it you will catch those flaws
    [EDIT]next time use code tags and indent[/EDIT]

  3. #3
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Thanks for the code, but unfortunately, to stick with the curriculum, I have to use sscanf.
    Semper Fi!

  4. #4
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    the same way
    Code:
    if((sscanf(buffer,"%i",&x)!=1))

  5. #5
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    You are resetting the error variable each time you enter the loop.
    Code:
    error = 0;
    Move this line up (must be before the for loop).

    b.t.w. please change [END CODE] to [/CODE]

  6. #6
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    I tried moving

    Code:
               error = 0;
    as you suggested. But when I put it above the for loop, the program prematurely terminated. I wasn't sure where to put it, so I tried a couple of places (I know....that is weak).
    However, when I changed the return value from 0 to 1, I was met with some moderate success. Now it will evaluate the first and last characters entered, such as r55 will be rejected, and 55r will be rejected, but still, not 5r5.
    I messed around with the code linuxdude provided, and it appears to do the same thing. Is there a reason why 5r5 can't be rejected as well?

    btw, my bad for the newbie misteakes. Thanks for the gentle nudge to let me know.

    RedZippo
    Semper Fi!

  7. #7
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Using as much as your code as I could:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    #define MAXLINE 100 
    
    int main(void)
    {
    char line[MAXLINE]; 
    int n; 
    int i; 
    int length;
    int error = 0;
    
    
    do 
    {
      error=0;
      printf(" Enter a positive integer: \n"); 
      printf("\n");
      fgets(line, MAXLINE, stdin); 
    
      sscanf(line, "%d", &n);
      length = strlen(line); 
      if ( line[length-1] == '\n' )
      {
        --length;
        line[length]='\0';
      }
    
      for (i = 0; i < length; ++i) 
      {
          if(!isdigit(line[i]))
          {
            error = 1;
            break;
          }
      }
      if (error)
      {
        printf("\n Try again!");
      }
      else
      {
        printf("\n Looks like an integer to me. Thanks!\n");
      }
    } while (error);
    
    return 0;
    }
    The conditional to remove the newline is just something I like to do and not required. Though if you do get rid of it make sure to change the for loop to length - 1.

    Empty if statements are kinda pointless. If you aren't going to do anything when its true and are going to do something when its false you can use negation to simplify it.

    Also once you have found out that their is a character in the stream there is no real point in checking the rest of it.

  8. #8
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Outstanding Thantos..! Works like a dream. I will look at it in detail tomorrow morning and will probably have some questions.

    Btw- nice emblem! How can I get one? 2nd Bn, 7th Marines here, 1983-1987.
    Semper Fi!

  9. #9
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    I found it on the USMC site, croped it down a bit and am hosting it on my webserver.

    III MEF, MCB Butler, Base Telephone 1999-2002. "No comm to big, no comm to small, mess with us no comm at all"

  10. #10
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Originally posted by linuxdude
    A program that accepts only integers
    Code:
    #include <stdio.h>
    
    int main(void){
         int x;
         printf("Enter a number:  ");
         fflush(stdout);
         if((scanf("%d",&x))!=1){
             printf("You didn't enter a digit\n");
             return 1;
         }
         else{
              printf("You entered a digit\n");
         }
         return 0;
    }
    I thought you've been around long enough to read all the warnings against using scanf() for keyboard input? You should not use it because of all the buffer problems it causes. Just do a search on this board for hundreds of warnings!
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 04:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM