在 C++ 中将小写字符更改为大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22425825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing a lowercase character to uppercase in c++
提问by Manisha Singh Sanoo
Here is the code that i wrote. When i enter a lowercase character such as 'a', it gives me a blank character but afterwards it works well. Can you tell me what i did wrong? Thanks. :)
这是我写的代码。当我输入一个小写字符(例如“a”)时,它会给我一个空白字符,但之后它运行良好。你能告诉我我做错了什么吗?谢谢。:)
#include <iostream>
#include <string>
using namespace std;
int main()
{
char letter;
cout << "You will be asked to enter a character.";
cout << "\nIf it is a lowercase character, it will be converted to uppercase.";
cout << "\n\nEnter a character. Press . to stop: ";
cin >> letter;
if(islower(letter))
{
letter = isupper(letter);
cout << letter;
}
while(letter != '.')
{
cout << "\n\nEnter a character. Press . to stop: ";
cin >> letter;
if(islower(letter))
{
letter = toupper(letter);
cout << letter;
}
}
return 0;
}
回答by herohuyongtao
Because you print a bool
value (i.e. false
, aka, NUL
characterhere) in the first time.
因为你打印一个bool
值(即false
,又名NUL
性格这里)在第一时间。
You should change
你应该改变
letter = isupper(letter);
to
到
letter = toupper(letter);
回答by Marius Bancila
Look here:
看这里:
if(islower(letter))
{
letter = isupper(letter);
cout << letter;
}
If the character is lower, then you assigned it the return value of isupper
. That should be 0. So you print a null character.
如果字符较低,则您为其分配了返回值isupper
. 那应该是 0。所以你打印一个空字符。
Why don't you just call toupper
for every character that you enter? If it's lower it will convert it, if it is already upper it won't do anything.
为什么不直接调用toupper
输入的每个字符?如果它较低,它将转换它,如果它已经较高,则不会做任何事情。
回答by Rishi
In case you want you own algorithm:
如果您想拥有自己的算法:
#include<iostream>
#include<string>
using namespace std;
int main()
{
char ch = '/0';
string input("Hello, How Are You ?");
for(size_t i=0; i<input.length(); i++)
{
if(input[i]>=97 && input[i]<=122)
{
ch=input[i]-32;
}
else
{
ch = input[i];
}
cout << ch;
}
return 0;
}
回答by hmofrad
Generally speaking to convert a lowercase character to an uppercase, you only need to subtract 32 from the lowercase character as this number is the ASCII code difference between uppercase and lowercase characters, e.g., 'a'-'A'=97-67=32
.
一般来说,将小写字符转换为大写字符,只需将小写字符减去 32,因为这个数字是大写和小写字符之间的 ASCII 码差异,例如,'a'-'A'=97-67=32
。
char c = 'b';
c -= 32; // c is now 'B'
printf("c=%c\n", c);
Another easy way would be to first map the lowercase character to an offset within the range of English alphabets 0-25
i.e. 'a' is index '0' and 'z' is index '25' inclusive and then remap it to an uppercase character.
另一种简单的方法是首先将小写字符映射到英文字母范围内的偏移量,0-25
即 'a' 是索引 '0','z' 是索引 '25',然后将其重新映射到大写字符。
char c = 'b';
c = c - 'a' + 'A'; // c is now 'B'
printf("c=%c\n", c);