Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我在从命令行参数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");
    }

}

最佳答案

到目前为止,当起始字符为字母时,即使存在数字,它也会接受整个字符串由字母组成的输入。


您的问题是此循环,我在其中删除了注释以使问题更清楚:

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: ");

10-07 13:01
查看更多