Author Topic: c programming handling inputed variables that are not an integer <solved>  (Read 1458 times)

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
I am writing the following code. The math part and number inputs will be added later.

Right now, its just looking at an option menu. I was able to detect invalid option numbers (integers) entered. However, how do I handle if the user enters (a non integer) letters or symbols? example invalid inputs : A n ab12 ( | ,

Basically I want to limit the acceptable inputs to 1, 2, 3, or 4 only and nothing else from the keyboard.

I tried searching google, but I haven't had much luck.

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library


int main()  //identifies the main program
{
          /* Declare variables    */
          
          int method;
          

          /* Ask User what to do with those numbers.       */
          /* 1 = Calculate the sum and average             */
          /* 2 = Calculate the product                     */
          /* 3 = Calculate the square of each number       */
          /* 4 = Calculate the square root of each number  */

          printf("Enter a method to calculate the three numbers entered.\n");
          printf("1 = Calculate the sum and average of the three numbers\n");
          printf("2 = Calculate the product of the three numbers\n");
          printf("3 = Calculate the square of each number\n");
          printf("4 = Calculate the square root of each number\n");
          scanf ("%i",&method);

  
          /* Perform Operation requested by user. */      
          /* Report an error if any other number is entered*/

          //  If the value entered is 0 or > 4, program ends
          if (method==0 || method>4){
             printf ("Method entered does not match option 1, 2, 3, or 4\n");
             goto end;
             }

//INSERT CODE THAT CAN HANDLE NON-INTEGERS VALUES
//INSERT CODE THAT CAN HANDLE NON-INTEGERS VALUES
//INSERT CODE THAT CAN HANDLE NON-INTEGERS VALUES
//INSERT CODE THAT CAN HANDLE NON-INTEGERS VALUES
            
        
          if (method==1 || method==2 || method==3 || method ==4){
             printf ("Method entered DOES match option 1, 2, 3, or 4\n");
             }
        
         printf("Option number %i was enterd.\n", method);
          
          end:
              
          getchar ();
          getchar ();
          
          /* Exit program */
          return 0;
}
          
          
    

« Last Edit: February 03, 2011, 04:04:53 PM by docnascar »
My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
Re: c programming handling inputed integers that are not a number
« Reply #1 on: February 03, 2011, 11:03:56 AM »
This section is only so I can see what is going on. Its not how I am going to proceed with the code.

Code: [Select]
          if (method==1 || method==2 || method==3 || method ==4){
             printf ("Method entered DOES match option 1, 2, 3, or 4\n");
             }
         
         printf("Option number %i was enterd.\n", method);

My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p

Offline muungwana

  • Hero Member
  • *****
  • Posts: 6212
Re: c programming handling inputed integers that are not a number
« Reply #2 on: February 03, 2011, 11:33:37 AM »
what program do you use to write your code in?

First, it is generally not recommended to use the "goto" statement and you should know your code path need to be redone if you find your self in need of the statement.

second, your checks fail to test for negative numbers, what if a user enter "-5"? your code path will go to "HANDLE NON-INTEGERS VALUES" area and this will cause a bug.

your code checks should be simple, you know what you are interested, just check for what you want and discard everything else, as i did below

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library


int main()  //identifies the main program
{
    char method;

    char *instructions = "Enter a method to calculate the three numbers entered.\n \
    1 = Calculate the sum and average of the three numbers\n \
    2 = Calculate the product of the three numbers\n \
    3 = Calculate the square of each number\n \
    4 = Calculate the square root of each number\n\0" ;

    printf("%s",instructions) ;
    scanf ("%c",&method);

    if ( method > '0' && method < '5' )
    {
printf("acceptable input\n") ;
    }else{
printf("unacceptable input\n") ;
    }
    
    return 0 ;
}
« Last Edit: February 03, 2011, 11:39:23 AM by muungwana »
.. 3 things are certain in life : death, taxes and software bloat ..
.. tell me something i don't know, something i can use as i struggle to reason with the world around me ..

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
Re: c programming handling inputed varaibles that are not an integer
« Reply #3 on: February 03, 2011, 01:23:29 PM »
Thanks!
I use devc++ on my windows machine and geany on my linux machine. Today I've been using my windows machine.

Thanks for the help. I'm a real beginner here.

I haven't used the char function.  I ran your code separate and it works great. I added the math part (if options, not shown below to keep it simple) with your code, but my program won't wait for the scanf of the method now.

How do I "if" a char variable? My way doesn't seem to work. Method = G

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library
#include <math.h>  //preprocessor command to include the math header library

int main()  //identifies the main program
{
    /* Declare variables    */
    char method;
                  
    char *instructions = "Enter a method to calculate the three numbers entered.\n \
    1 = Calculate the sum and average of the three numbers\n \
    2 = Calculate the product of the three numbers\n \
    3 = Calculate the square of each number\n \
    4 = Calculate the square root of each number\n\0" ;

    printf("%s",instructions) ;
    scanf ("%c",&method);

    if ( method > '0' && method < '5' )
    {
printf("acceptable input\n") ;
    }else{
printf("unacceptable input\n") ;
    }
 
    printf("Method = %c\n");
            
    /* Perform Operation requested by user. */      
    if (method=1){
       printf("OPTION 1 WAS ENTERED\n");
       }
          
    if (method=2){
       printf("OPTION 2 WAS ENTERED\n");
       }
              
    getchar ();
    getchar ();
          
    /* Exit program */
    return 0;
}
          
          
« Last Edit: February 03, 2011, 01:59:05 PM by docnascar »
My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
Re: c programming handling inputed varaibles that are not an integer
« Reply #4 on: February 03, 2011, 01:28:46 PM »
This was my original assignment so you can understand what I was doing. Its done now and graded, but I'm just trying to improve on it for my personal knowledge of how to make it better.

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library
#include <math.h>  //preprocessor command to include the math header library

int main()  //identifies the main program
{
          /* Declare variables    */
          double num1, num2, num3, sumT, prodT, avgT, sq1, sq2, sq3, sqRoot1, sqRoot2, sqRoot3;
          int method;
          
          /* Have the user Enter the 3 numbers             */
       printf("Enter 3 number and choose Calculation method \n\n");
          printf("Enter the first number\n");
          scanf ("%lf",&num1);
          printf("Enter the second number\n");
          scanf ("%lf",&num2);
          printf("Enter the third number\n");
          scanf ("%lf",&num3);

          /* Ask User what to do with those numbers.       */
          /* 1 = Calculate the sum and average             */
          /* 2 = Calculate the product                     */
          /* 3 = Calculate the square of each number       */
          /* 4 = Calculate the square root of each number  */

          printf("Enter a method to calculate the three numbers entered.\n");
          printf("1 = Calculate the sum and average of the three numbers\n");
          printf("2 = Calculate the product of the three numbers\n");
          printf("3 = Calculate the square of each number\n");
          printf("4 = Calculate the square root of each number\n");
          scanf ("%i",&method);
          
          
          /* Compute the values of the three numbers */
          sumT=num1+num2+num3;
          prodT=num1*num2*num3;
          avgT=sumT / 3;
          sq1=num1*num1;
          sq2=num2*num2;
          sq3=num3*num3;
          sqRoot1=sqrt(num1);
          sqRoot2=sqrt(num2);
          sqRoot3=sqrt(num3);
  
          /* Perform Operation requested by user. */      
          /* Report an error if any other number is entered*/

          //  If the value entered is 0 or > 4, program ends
          if (method==0 || method>4){
             printf ("Method entered does not match option 1, 2, 3, or 4\n");
             goto end;
             }
        
          if (method==1){
             printf("The SUM of the three values is: %5.3lf \n", sumT);
             printf("The AVERAGE of the three values is: %5.3lf \n", avgT);
             }
          
          if (method==2){
              printf("The PRODUCT of the three values is: %5.3lf \n", prodT);
              }

          if (method==3){
              printf("The SQUARE of each number is: %5.3lf %5.3lf %5.3lf \n", sq1, sq2, sq3);
              }

          if (method==4){
              printf("The SQUARE ROOT of each number is: %5.3lf %5.3lf %5.3lf \n", sqRoot1, sqRoot2, sqRoot3);
              }
          
          end:
              
          getchar ();
          getchar ();
          
          /* Exit program */
          return 0;
}
          
          

My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p

Offline muungwana

  • Hero Member
  • *****
  • Posts: 6212
Re: c programming handling inputed varaibles that are not an integer
« Reply #5 on: February 03, 2011, 02:03:54 PM »

what do you mean by "but my program won't wait for the scanf of the method now"?

There is an error in one of your lines
Code: [Select]
printf("Method = %c\n");
should be
Code: [Select]
printf("Method = %c\n",method);

characters are usually included in single quotes and hence you test for characters using single quotes, so character "2" is '2' and hence the test will be "if (method == '2')"

the test for each input should be something like this

if ( method ==  '1' )

equal conditional statements usually is checked with double "=" as in "=="

you should try to know how to properly structure the flow of your code.

if-else condition statement is better than your single test for each input.

Since you are comparing a single input, a swith use is a better candidate.

The code is support to work as expected and is supposed to look neater and "case" statement here works best.

my code is below to show you how you to use "if-else" and "switch"

Not that both of the them only checks for valid input and discard the rest of input as unacceptable without paying attention what they are.

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library
#include <math.h>  //preprocessor command to include the math header library

int main()  //identifies the main program
{
    /* Declare variables    */
    char method;
                   
    char *instructions = "Enter a method to calculate the three numbers entered.\n \
    1 = Calculate the sum and average of the three numbers\n \
    2 = Calculate the product of the three numbers\n \
    3 = Calculate the square of each number\n \
    4 = Calculate the square root of each number\n\0" ;

    printf("%s",instructions) ;
    scanf ("%c",&method);

    if ( method > '0' && method < '5' )
    {
printf("acceptable input\n") ;
    }else{
printf("unacceptable input\n") ;
    }
 
    printf("Method = %c\n",method);
             
    /* Perform Operation requested by user. */     
    if (method == '1'){
       printf("OPTION 1 WAS ENTERED\n");
       }else if ( method == '2'){
printf("OPTION 2 WAS ENTERED\n");
       }else if ( method == '3'){
          printf("OPTION 3 WAS ENTERED\n");
       } else if (method == '4'){   
       printf("OPTION 4 WAS ENTERED\n");
       }else{
printf("AN ILLEGAL OPTION WAS ENTERED\n");
       }
             
      switch(method)
      {
case '1' : printf("OPTION 1 WAS ENTERED\n"); break ;
case '2' : printf("OPTION 2 WAS ENTERED\n"); break ;
case '3' : printf("OPTION 3 WAS ENTERED\n"); break ;
case '4' : printf("OPTION 4 WAS ENTERED\n"); break ;
default :  printf("AN ILLEGAL OPTION WAS ENTERED\n");
      }
     
    getchar ();
    getchar ();
         
    /* Exit program */
    return 0;
}

.. 3 things are certain in life : death, taxes and software bloat ..
.. tell me something i don't know, something i can use as i struggle to reason with the world around me ..

Offline muungwana

  • Hero Member
  • *****
  • Posts: 6212
Re: c programming handling inputed varaibles that are not an integer
« Reply #6 on: February 03, 2011, 02:15:09 PM »

you are taking a class? so some of the things i have said like what control structure is better where maybe in your future classes. dont drop out  :D

.. 3 things are certain in life : death, taxes and software bloat ..
.. tell me something i don't know, something i can use as i struggle to reason with the world around me ..

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
Re: c programming handling inputed varaibles that are not an integer
« Reply #7 on: February 03, 2011, 03:19:42 PM »
Its getting better.. and thanks for the tips. Yeh this is only my third class (intro to C).


what do you mean by "but my program won't wait for the scanf of the method now"?


After I add the ability to enter a variable for num1, my program skips to the end of the method option and says "unacceptable input".

Code: [Select]
#include <stdio.h> //preprocessor command to include the standard I/O header library
#include <math.h>  //preprocessor command to include the math header library

int main()  //identifies the main program
{
    /* Declare variables    */
    double num1;
    char method;
   
    printf("Enter a number.\n");
    scanf ("%lf",&num1);
               
    char *instructions = "Enter a method to calculate the three numbers entered.\n \
    1 = Calculate the sum and average of the three numbers\n \
    2 = Calculate the product of the three numbers\n \
    3 = Calculate the square of each number\n \
    4 = Calculate the square root of each number\n\0" ;

    printf("%s",instructions) ;
    scanf ("%c",&method);

    if ( method > '0' && method < '5' )
    {
printf("acceptable input\n") ;
    }else{
printf("unacceptable input\n") ;
    }
 
    printf("Method = %c\n", method);
             
    /* Perform Operation requested by user. */     
    if (method=='1'){
       printf("OPTION 1 WAS ENTERED\n");
       printf("The number entered was %4.2lf\n", num1);
       }
         
    if (method=='2'){
       printf("OPTION 2 WAS ENTERED\n");
       printf("The number entered was %4.2lf\n", num1);
       }
             
    getchar ();
    getchar ();
         
    /* Exit program */
    return 0;
}
         
         

My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p

Offline muungwana

  • Hero Member
  • *****
  • Posts: 6212
Re: c programming handling inputed varaibles that are not an integer
« Reply #8 on: February 03, 2011, 03:55:13 PM »

do you see the line with this code?

    printf("%s",instructions) ;
    scanf ("%c",&method);

change it to this:

    printf("%s",instructions) ;
    scanf ("%c",&method);
    scanf ("%c",&method);

you need two "scanf", the first one to capture the new line character remained in the buffer when scanf was called the first time to put user input to num1.The second will then ask a user for an input.

scanf can sometimes leave behind data in the buffer and a second call to scanf can read from the buffer instead of from the keyboard and this is what happened to you. flashing the buffer before next call to scanf is more secured.
.. 3 things are certain in life : death, taxes and software bloat ..
.. tell me something i don't know, something i can use as i struggle to reason with the world around me ..

Offline muungwana

  • Hero Member
  • *****
  • Posts: 6212
Re: c programming handling inputed varaibles that are not an integer
« Reply #9 on: February 03, 2011, 04:02:03 PM »

did you ask why you are calling "getchar()" twice?  :D

The first call reads from the buffer(left overs from previous call) and clears it and the second one reads from the new buffer just entered from the keyboard. Those two calls were necessary because some calls dont clear the buffer and it messes up subsequent calls.

.. 3 things are certain in life : death, taxes and software bloat ..
.. tell me something i don't know, something i can use as i struggle to reason with the world around me ..

Offline docnascar

  • Sr. Member
  • ****
  • Posts: 465
Re: c programming handling inputed varaibles that are not an integer
« Reply #10 on: February 03, 2011, 04:04:01 PM »

did you ask why you are calling "getchar()" twice?  :D

The first call reads from the buffer(left overs from previous call) and clears it and the second one reads from the new buffer just entered from the keyboard. Those two calls were necessary because some calls dont clear the buffer and it messes up subsequent calls.



Yup. I get it!

Hey thanks so much. It works now.
My main PCLINUXOS PC:
KDE Mini
AMD FX-6300 (3.5G / 6 core)
MSI 970A-G46 AM3+ MOBO
G.SKILL Sniper Series 8GB (2 x 4GB) 1866 (PC3 14900)
ECS GeForce GT 440 (Fermi) 512MB 128-bit GDDR5
Seagate Barracuda ST1000DM003 1TB 7200 RPM SATA
SAMSUNG DVD Burner SATA Model SH-224BB
POWERUP PU-550 (550W) p