14 Replies - 2521 Views - Last Post: 22 March 2011 - 10:32 PM Rate Topic: -----

#1 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Character check in C

Posted 22 March 2011 - 12:21 PM

My program prompts the user to enter a numeric value and I've been trying to put in a piece of code that checks if the input is a numeric value or not, if it isn't the program is to then tell the user that the data entered is invalid and display a prompt to re-enter the data, and if it is valid the program is to continue through the rest of the process. I tried to do this but the program starts over when I enter the invalid datatype. How do I get it to work properly and what did I do wrong? Here's the part of the code thats giving me the problem:
      printf("\n*                    Please enter your TRN number.                    *\n");
      scanf("%d", &trn);
      if (isalpha(trn))
      { 
       do{ 
            printf("\n INVALID INPUT, PRESS ENTER TO TRY AGAIN \n\n");
            printf("Please re-enter trn\n");
            scanf("%d", trn);
            system("clrs");
          } while (isalpha(trn));
       }
       else
       { 
         system("cls");


Also, I want the program to continue requesting the proper input until it is given.

Is This A Good Question/Topic? 0
  • +

Replies To: Character check in C

#2 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2412
  • View blog
  • Posts: 4,545
  • Joined: 30-May 10

Re: Character check in C

Posted 22 March 2011 - 12:43 PM

isalpha works on characters, not numbers.

You need something like this
while ( scanf("%d", &trn) != 1 ) {
  int temp;
  while ( (temp=getchar()) != EOF && temp != '\n' );    // ditch bad input
  if ( temp == EOF ) {
    printf("Bye\n");
    break;  // or exit()
  }
  printf("\n INVALID INPUT, PRESS ENTER TO TRY AGAIN \n\n");
  printf("Please re-enter trn\n");
}


First, you check the return result of scanf() to see if any conversion was successful.
Was This Post Helpful? 2
  • +
  • -

#3 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 07:48 PM

Gee thanks, One problem though It only works when you enter a invalid input 1st then enter the correct input. When I enter the correct input nothing happens.

And also explain what the line means, Im all new to this.

while ( scanf("%d", &trn) != 1 ) 



Gee thanks, One problem though It only works when you enter a invalid input 1st then enter the correct input. When I enter the correct input nothing happens.

And also explain what the line means, Im all new to this.

while ( scanf("%d", &trn) != 1 ) 



I don't understand exactly why you placed the scanf not equal to zero
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 07:57 PM

Quote

And also explain what the line means, Im all new to this.


That is getting a value from the user checking the return value of scanf. See this link.

Quote

Return Value
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens.
In the case of an input failure before any data could be successfully read, EOF is returned.


Quote

One problem though It only works when you enter a invalid input 1st then enter the correct input. When I enter the correct input nothing happens.

What do you mean by nothing happens?

The code should only print the error messages if you entered an improper value. If you entered a valid number then the value you entered should now be contained in your variable trn.

Jim

This post has been edited by jimblumberg: 22 March 2011 - 07:58 PM

Was This Post Helpful? 1
  • +
  • -

#5 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 08:14 PM

There's another set of code that the program is suppose to run after making sure the input of the correct data type, but when I do enter the correct data type and press enter... nothing happens. See photo attached

photo:

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#6 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 08:15 PM

Post your current code along with complete error/warning messages if any.

Jim
Was This Post Helpful? 0
  • +
  • -

#7 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 08:23 PM

#include <stdio.h>
#include <cstring>
#include <stdlib.h>

/* decleration of functions */

char loanlevel(int);
int level1check(float);
int level2check(float);
int level3check(float);

int main()
{
    /* Declaration of variables */
    char fn[10], ln[10];
    float mi;
    char r;
    int lev, acceptedlevl1[100], acceptedlevl2[100], acceptedlevl3[100], i, a=0, b=0, c=0, d=0, trn, ll, num1, denied[100];
    do{
      printf("***********************************************************************\n");
      printf("*                      Welcome to CORE Corporation                    *");   /* Welcoming header. */
      printf("\n***********************************************************************\n");
      printf("\n\n*              This program will carry you through a step             *\n*              by step process to help you fill out you               *");
      printf("\n*              mortgage application. Please enter your                *\n*              information as accurately as possible.                 *\n");   /* Introduction to th programd */
      printf("\n\n*  Core Coporation has three different levels of loans.  The amount   *\n*  of money to be dispersed depends on the loan level. Each of these  *");
      printf("\n*  loan levels have a criteria which must be met in order for the     *\n*  loan to be granted and each loan level requires a different monthly*\n*  payment."); /* Explnation of different process by which a loand is granted */
      printf(" The table below shows the different levels and their      *\n*  corresponding requirements.  Chose the loan that best suites your  *\n*  need and");
      printf(" affordablity.                                             *\n");
      /* Input of data for processing. */
      printf("\n\n*                    Please enter your full name.                     *\n");
      scanf("%s%s", &fn, &ln);
      system("cls");
      printf("\n*                    Please enter your TRN number.                    *\n");
      scanf("%d", &trn);
      system("cls");
      while ( scanf("%d", &trn) != 1 ) 
      {
        int temp;
        while ( (temp=getchar()) != EOF && temp != '\n' );    // ditch bad input
        if ( temp == EOF )
        {
          printf("Bye\n");
          break;  // or exit()
        }
      printf("\nINVALID INPUT\n\n");
      printf("Please re-enter trn\n");
      }
      /* A table which allows the user to see clearly what his/her choices are. */

      printf("\n ___________________________________________________________________\n|Loan Level|  Amount   |       Requirements       | Monthly payment   |\n");
      printf(" ___________________________________________________________________\n");
      printf("\n| Level  1 |   Up to   |  Monthly Income: $60,000 |                   |\n|          | 4,000,000 |  upwards                 | $15K for 21 years |\n\n");
      printf("| Level  2 |   Up to   |  Monthly Income: $100K   |                   |\n|          | 7,000,000 |  upwards                 | $40K for 20 years |\n\n");
      printf("| Level  3 |   Up to   |  Monthly Income: $250K   |                   |\n|          | 10,000,000|  upwards                 | $50K for 19 years |");
      printf("\n _____________________________________________________________________\n");
      printf("\n*   Please enter the number corresponding to your desired loan level  *");
      printf("\n ______________________________________________________________________");
      printf("\n|                NUMBERS FOR CORRESPONDING LOAN LEVELS                |");
      printf("\n|                       Level 1      :       1                        |");
      printf("\n|                       Level 2      :       2                        |");
      printf("\n|                       Level 3      :       3                        |");
      printf("\n ______________________________________________________________________\n");
      scanf("%d", &ll);
      system("cls");
      printf("\n*                    Please enter your monthly income.                *\n$");
      scanf("%f", &mi);
      system("cls");

      r = loanlevel(ll);
      switch(r)
      {
        case 'A':  /* The variable are processed and the appropriate resposes are given for loan level 3. */
        lev = level1check(mi);
        if (lev == 123)
        {
          printf("Your request for the loan entered has been accepted!\n");
          acceptedlevl1[a]=trn;
          a++;
          printf("\nFor the next application press ENTER");
        }
        else
        {
          printf("Your request for the loan entered has been denied.\n");
          denied[d] = trn;
          d++;
          printf("\nFor the next application press ENTER");
        }
        break;
        case 'B':  /* The variable are processed and the appropriate resposes are given for loan level 2. */
        lev = level2check(mi);
        if (lev == 456)
        {
           printf("Your request for the loan entered has been accepted!\n");
           acceptedlevl2[b]=trn;
           b++;
           printf("\nFor the next application press ENTER");
        }
        else
        {
           printf("Your request for the loan entered has been denied.\n");
           denied[d]=trn;
           d++;
           printf("\nFor the next application press ENTER");
        }
        break;
        case 'C':  /* The variable are processed and the appropriate resposes are given for loan level 3. */
          lev = level3check(mi);
          if (lev == 789)
            {
              printf("Your request for the loan entered has been accepted!\n");
              acceptedlevl3[c]= trn;
              c++;
              printf("\nFor the next application press ENTER");
            }
            else
            {
              printf("Your request for the loan entered has been denied.\n");
              denied[d]=trn;
              d++;
              printf("\nFor the next application press ENTER");
            }
        break;
        default:
          printf("INVALID CODE\n");
        break;
       }
       getchar();
       getchar();  /* This allows the applicant to start a new applicantion by pressing enter. */
       system("cls");
    }while(trn != 000); /* this allows an administratpr to end the cycle by entering the code "000" and allows the program to print the contents of the arrays. */

    /* The following instructions print the names of the people who were denied and accpected for loans one, two and three. */

    printf("\n\nThe number of people granted the level 1 loan is %d and the TRN of these applicants are;\n", a);
    for (i=0; i <=a-1;i++)
    {
       printf("%d\n", acceptedlevl1[i]);
    }
    printf("\n\nThe number of people granted the level 2 loan is %d and the TRN of these applicants are;\n", B)/>;
    for (i=0; i <=b-1;i++)
    {
       printf("%d\n", acceptedlevl2[i]);
    }
    printf("\n\nThe number of people granted the level 3 loan is %d and the TRN of these applicants are;\n", c);
    for (i=0; i <=c-1;i++)
    {
       printf("%d\n", acceptedlevl3[i]);
    }
    printf("\n\nThe number of people denied is %d and the TRN of these applicants are;\n", a);
    for (i=0; i <=d-1;i++)
    {
       printf("%d\n", denied[i]);
    }
    getchar();
    getchar();
}



/* Functions */

char loanlevel(int q) /* Function which identifies which loan level the applicant requested. */
{
    char e;
    if (q == 1)
    {
      e = 'A';
    }
       else
       {
         if (q == 2)
         {
           e = 'B';
         }
         else
         {
           if (q == 3)
           {
             e = 'C';
           }
         }
       }
    return(e);
}

int level1check(float r) /* Function which tests if the monthly income meets the requirements of the level 1 loan. */
{
    int q;
    if (r >= 60000)
      {
        q = 123;
      }
      return(q);
}

int level2check(float s) /* Function which tests if the monthly income meets the requirements of the level 2 loan. */
{
    int t;
    if (s >= 100000)
      {
        t = 456;
      }
      return(t);
}

int level3check(float u) /* Function which tests if the monthly income meets the requirements of the level 3 loan. */
{
    int v;
    if (u >= 250000)
      {
        v = 789;
      }
      return(v);
}



I appreciate the help.
Was This Post Helpful? 0
  • +
  • -

#8 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 08:42 PM

Is this a C or C++ program. If it is a C program then this #include <cstring> is the wrong include file it should be #include <string.h>.
The cstring header is a standard C++ header file.

When I compile your code I get the following warnings:

Quote

main.c||In function ‘main’:|
main.c|31|warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[10]’|
main.c|31|warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘char (*)[10]’|
main.c|18|warning: unused variable ‘num1’|
main.c|156|warning: control reaches end of non-void function|


Line 31 is: scanf("%s%s", &fn, &ln); and since your variables are C-strings your do not need the ampersand (&).

Also you do not need lines 34 and 35, these lines are replaced by the lines 36 - 47.

Jim
Was This Post Helpful? 1
  • +
  • -

#9 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 09:02 PM

thanks ALOT, works ALMOST perfect. The thing is The program starts over if numbers are a the 1st part of the input, but the message comes up when the letters are 1st. It should prompt the user to re-enter once letters are in the input at any position, whether at the beginning, middle or back. Other than that, It works perfect. Also, how do you get to see the errors like that, mine doesn't show that, I'm using DevC by the way.
Was This Post Helpful? 0
  • +
  • -

#10 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 09:19 PM

You need to check your compiler documentation on how to turn on warnings. Also you may want to consider changing your compiler since it is fairly old and not being maintained any longer.

Quote

The thing is The program starts over if numbers are a the 1st part of the input, but the message comes up when the letters are 1st. It should prompt the user to re-enter once letters are in the input at any position, whether at the beginning, middle or back.


I would just empty the input buffer, throwing away any remaining characters in the buffer.
while(getchar() != '\n');


Jim

This post has been edited by jimblumberg: 22 March 2011 - 09:20 PM

Was This Post Helpful? 0
  • +
  • -

#11 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 09:38 PM

LOL remember when I said I'm new to this, where would you put that piece of code?

Another suggested C compiler?

This post has been edited by Top_Noob: 22 March 2011 - 09:39 PM

Was This Post Helpful? 0
  • +
  • -

#12 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 09:46 PM

Somewhere after your loop maybe around line 49.

You could check out Visual C from Microsoft or Code::blocks with the mingw compiler.
(check the FAQ there is a list of several compilers available free to download). If you go with CodeBlocks be sure to download the version with the compiler.

Jim
Was This Post Helpful? 0
  • +
  • -

#13 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 10:02 PM

Right there? Because I did that and I'm still having the same problem.
#include <stdio.h>
#include <cstring>
#include <stdlib.h>

/* decleration of functions */

char loanlevel(int);
int level1check(float);
int level2check(float);
int level3check(float);

int main()
{
    /* Declaration of variables */
    char fn[10], ln[10];
    float mi;
    char r;
    int lev, acceptedlevl1[100], acceptedlevl2[100], acceptedlevl3[100], i, a=0, b=0, c=0, d=0, trn, ll, num1, denied[100];
    do{
      printf("***********************************************************************\n");
      printf("*                      Welcome to CORE Corporation                    *");   /* Welcoming header. */
      printf("\n***********************************************************************\n");
      printf("\n\n*              This program will carry you through a step             *\n*              by step process to help you fill out you               *");
      printf("\n*              mortgage application. Please enter your                *\n*              information as accurately as possible.                 *\n");   /* Introduction to th programd */
      printf("\n\n*  Core Coporation has three different levels of loans.  The amount   *\n*  of money to be dispersed depends on the loan level. Each of these  *");
      printf("\n*  loan levels have a criteria which must be met in order for the     *\n*  loan to be granted and each loan level requires a different monthly*\n*  payment."); /* Explnation of different process by which a loand is granted */
      printf(" The table below shows the different levels and their      *\n*  corresponding requirements.  Chose the loan that best suites your  *\n*  need and");
      printf(" affordablity.                                             *\n");
      /* Input of data for processing. */
      printf("\n\n*                    Please enter your full name.                     *\n");
      scanf("%s%s", fn, ln);
      system("cls");
      printf("\n*                    Please enter your TRN number.                    *\n");
      while ( scanf("%d", &trn) != 1 ) 
      {
        int temp;
        while ( (temp=getchar()) != EOF && temp != '\n' && getchar() !='\n');    // Ditch bad input
        if ( temp == EOF )
        {
          break;  // or exit()
        }
      printf("\nINVALID INPUT\n\n");
      printf("Please re-enter trn\n");
      }
      system("cls");
      /* A table which allows the user to see clearly what his/her choices are. */
      while(getchar() != '\n');

Was This Post Helpful? 0
  • +
  • -

#14 jimblumberg   User is offline

  • member icon

Reputation: 5788
  • View blog
  • Posts: 17,697
  • Joined: 25-December 09

Re: Character check in C

Posted 22 March 2011 - 10:16 PM

Putting it there will throw away anything left in the buffer and continue on. You should have some number in your variable. Up to this point you have never said what is a valid entry. The user can enter any number so unless you want to limit the user to some number range just continuing would be a valid way to handle this problem. Another option would be telling the user they entered an invalid entry and then exit the program.

Jim
Was This Post Helpful? 0
  • +
  • -

#15 Top_Noob   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 23-February 11

Re: Character check in C

Posted 22 March 2011 - 10:32 PM

okay but how do I get it to print invalid input and prompt the user to re-enter the number if say "24nse" was entered?

This post has been edited by Top_Noob: 22 March 2011 - 10:33 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1