检查字母是否是标准输入中的大写字母

时间:2017-11-12 21:01:16

标签: c

我的任务是从标准输入中将标记读入缓冲区,并检查字符串是否有名称。名称以大写开头,所有其他字母必须是小写。这是我的代码。

bool nextName(char * buffer, int len)
{
    bool name = false;    //name = false checks if the loop is inside name
    int i = 0;            //number of a char in the name
    char c;               //used for loading a char

    while((c = getchar()) != EOF)
    {
        while(c == ',' || c == '"')             //cuts off commas
        {
            c = getchar();
        }

        if(name && !islower(c))    //If name is set to true and "c" is not a lowercase(it's an uppercase for example)
        {                          //it means it's not a name(I thought that will work)
            buffer[i++] = '\0';
            return true;
        }

        if(!name && isupper(c))     //First char of a name
        {
            name = true;
        }

        //Override guard
        if(i == len - 1)
        {
            buffer[i++] = '\0';
            return false;
        }

        buffer[i] = c; // Add char to the string
        i++;    // It's not "for loop" because incrementation can happen only when added
        //       char to string.
    }

    //End of file
    if(name)
    {
        return true;
    }
    return false;
}

我认为这是一个if语句

if(name && !islower(c))    //If name is set to true and "c" is not a lowercase(it's and uppercase for example)
        {                          //it means it's not a name
            buffer[i++] = '\0';
            return true;
        }

将检查变量名是否是正确的名称(一个是大写,另一个是小写)。我不知道为什么它不起作用。

输入

It is an Example

我期待这样的输出:

It
Example

1 个答案:

答案 0 :(得分:0)

此代码适用于此任务。

bool nextName(char * buffer, int len)
{
bool name = false;    //name = false checks if the loop is inside name
int i = 0;            //number of a char in the name
int c;               //used for loading a char

while((c = getchar()) != EOF)
{
    if (!name && !isupper(c)) continue;     //There hasn't been any name in standard input yet

    if(!name && isupper(c))     //First char of a name
    {
        name = true;
    }

    else if(name && !islower(c))        //End of the name
    {
        buffer[i++] = '\0';
        return true;
    }

    //Override guard
    if(i == len - 1)
    {
        buffer[i++] = '\0';
        return false;
    }

    buffer[i] = c; //Add "c" to string
    i++;
}

//End of a file
if(name)
{
    return true;
}
return false;
}
PS:对不起,我很抱歉。我试图修复此代码。谢谢你的帮助。