这是我写的代码。当我输入一个小写字符,如"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 << "nnEnter a character. Press . to stop: ";
cin >> letter;
if(islower(letter))
{
letter = isupper(letter);
cout << letter;
}
while(letter != '.')
{
cout << "nnEnter a character. Press . to stop: ";
cin >> letter;
if(islower(letter))
{
letter = toupper(letter);
cout << letter;
}
}
return 0;
}
因为您第一次打印的是bool
值(即false
,即NUL
字符)
你应该修改
letter = isupper(letter);
letter = toupper(letter);
看这里:
if(islower(letter))
{
letter = isupper(letter);
cout << letter;
}
如果字符较低,则为其分配isupper
的返回值。它应该是0。输出一个空字符。
为什么不为你输入的每个字符调用toupper
呢?
一般来说,要将小写字符转换为大写字符,只需要从小写字符中减去32,因为这个数字是大写字符和小写字符之间的ASCII码差,例如'a'-'A'=97-67=32
。
char c = 'b';
c -= 32; // c is now 'B'
printf("c=%cn", c);
另一种简单的方法是首先将小写字符映射到英语字母0-25
范围内的偏移量,即:'a'为索引'0','z'为索引'25',然后将其重新映射为大写字符。
char c = 'b';
c = c - 'a' + 'A'; // c is now 'B'
printf("c=%cn", c);
如果你想要自己的算法:
#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;
}
在letter = isupper(letter);
中,检查变量letter
是否大写,要将其转换为大写,必须使用toupper()
letter = toupper(letter);
#include <iostream>
using namespace std;
main()
{
string name ;
cout<<"Lower Case: ";
cin>>name;
int size_of_string = name.size(); // to detrmine the looping times
cout<<"Upper case: ";
for(int i = 0 ,n = size_of_string ; i < n ; i++)
{
//check if the str[i] is lowercase
if(name[i] >= 'a' && name[i]<='z' )
{
//convert the Lowercase to uppercase via ASCI Chart
char a = name[i] - 32 ;
cout<<a;
}
//the user input was upperCase
else
cout<<name[i];
}
cout<<"n Good Bye!"<<endl;
return 0;
}