在每种情况下意外输出。我的解决方案出了什么问题?

时间:2013-12-13 13:43:20

标签: c++ string

问题131A - http://codeforces.com/problemset/problem/131/A 我的解决方案不是做问题所要求的,而是返回输入的相同字符串。我的解决方案出了什么问题。

我的解决方案:

#include<iostream>
#include<cstring>
using namespace std;
int i,a;
char input[101];
int main()
{
    cin>>input;
    a=0;
    for(i=0;input[i]!=NULL;i++) //To find number of uppercase letters.
    {
        if(isupper(input[i]))
        a++;
    }
    if((a==strlen(input))|((a==(strlen(input)-1))&(islower(input[0])))) //To check for accidental pressing of Caps Lock(Words like Jingle or jINGLE.).
    {
        toupper(input[0]);
        for(i=1;input[i]!=NULL;i++)
        {
            tolower(input[i]);
        }
        cout<<input;
    }
    else
    cout<<input;
}

3 个答案:

答案 0 :(得分:1)

toupper(input[0]);

不会将input[0]更改为大写,会返回大写的等效input[0]

尝试

input[0] = toupper(input[0]);
而不是(和其他每个toupper / tolower调用相同)。

答案 1 :(得分:1)

char toupper(char)char tolower(char)仅返回转换后的字符,并且不会修改传递的字符(它需要引用或指针使用)。而是使用:

input[0] = toupper(input[0]);
for(i=1;input[i]!=NULL;i++)
{
    input[i] = static_cast<char> ( tolower( static_cast<unsigned char>(input[i]) ) );
}
cout<<input;

答案 2 :(得分:1)

toupper()tolower()不会更改其参数,但会返回已更改的char。你必须写input[i] = toupper(input[i])。那么你不应该使用按位运算符进行有条件的检查。请改用||&&