lundi 3 décembre 2018

C Programm for reading char doesn't recognize correct entered strings.

hopefully, you're able to help me put. I'm currently struggling with an exercise my university told us to do. I have to write a program in C which scans in a string and reads it through a function called read_name(). The program should output whether the entered string is correct or not. The conditions for the string are:

  • The first character should be an uppercase letter.
  • All the other characters in the entered string have to be letters
  • The minimum length of the string has to be at least 2 elements
  • The maximum length of the string has to be 20 elements

I already wrote the program and it executes finely, but everytime I enter a string, regardless if it contains only letters, numbers or symbols like a comma, it always ouputs that the entered string is incorrect. But I thought I already wrote the program in a way, so that every possible wrong input would be recognized but every correct input shoul be displayed as correct.

I think my mistake is in the for-loop in the function "int read_name(char input[])". I can't change the declaration of this function because it was predefined by my university. Everything else can be changed. :)

I hope I explained my problem clearly enough. Thanks a lot in advance.

Here's the code of the program:

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

#define MAX_STRING 20
#define MIN_STRING 2
#define UPPERCASE_MIN_ASCII 65
#define UPPERCASE_MAX_ASCII 90
#define LOWERCASE_MAX_ASCII 122
#define LOWERCASE_MIN_ASCII 97

int read_name(char input[]);

int main(void)
{
        char pre_input[MAX_STRING];
        char status;

        printf("Please put in a string: ");
        gets(pre_input);

        status = read_name(pre_input);

        if(status == 0) {
                printf("Input was incorrect!");
        } else {
                printf("Input was correct");
        }
        return 0;
}

int read_name(char input[])
{
        int i, n;

        n = strlen(input);

        if (n < MIN_STRING)
                return 0;

        if (input[0] < UPPERCASE_MIN_ASCII || input[0] > UPPERCASE_MAX_ASCII)
                return 0;

        for (i = 1; i <= n; i++) {

                if (input[i] < UPPERCASE_MIN_ASCII || input[i] > LOWERCASE_MAX_ASCII) {
                        return 0;
                } else if (input[i] > UPPERCASE_MAX_ASCII && input[i] < LOWERCASE_MIN_ASCII) {
                        return 0;
                }
        }
        return 1;
}

Alex

Aucun commentaire:

Enregistrer un commentaire