仅在 C 中验证字母输入

validation for alphabetical input only in C

我在仅接受来自命令行参数 argv[1] 的字母字符时遇到问题。如果我插入字母后跟数字,这将被接受为有效输入,但我只需要接受字母。因此,如果用户输入类似: "Jack23" 我需要它显示为与“32214”相同的错误。截至目前,当起始字符是字母时它接受输入,就好像整个字符串由字母组成,即使存在数字也是如此。这是我目前所拥有的:

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


int main(int argc, string argv[])
{
    string plain_text;
    string key = argv[1];

    if (argc == 2)
    {
        // checks each character from second argument to see if it is an alphabetical character
        for (int i = 0, k = strlen(key); i < k; i++)
        {
            //if a non-alphabetical character is detected, the user is reprompted to enter a valid key
            if (!isalpha(key[i]))
            {
                printf("error, non alphabetic input detected, please input valid key");
                return 1;
            }

            // if user enters correct alphabetical key then we proceed with the request for valid plain text
            else
            {
                plain_text = get_string("plaintext: ");
            }

        }
    }
    else
    {
        printf("error, please input two arguments! Ex: ./test Try");
    }

}

As of right now it accepts inputs when the beginning character is a letter as if the whole string is composed of letters even when numbers are present.

你的问题是这个循环,我删除了注释以使问题更清楚:

for (int i = 0, k = strlen(key); i < k; i++)
{
    if (!isalpha(key[i]))
    {
        printf("error, non alphabetic input detected, please input valid key");
        return 1;
    }
    else
    {
        plain_text = get_string("plaintext: ");
    }
}

该循环将在字符串中找到字母字符后立即调用 get_string("plaintext: ")

您想将 else 部分移出循环并让循环验证 整个 输入字符串。

for (int i = 0, k = strlen(key); i < k; i++)
{
    if (!isalpha(key[i]))
    {
        printf("error, non alphabetic input detected, please input valid key");
        return 1;
    }
}

plain_text = get_string("plaintext: ");