【发布时间】:2017-01-31 14:48:35
【问题描述】:
所以这是我用来将小写转换为大写的程序,你能告诉我为什么我们使用这个东西吗?[(str[i]>=97 && str[i]
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{
clrscr();
char str[20];
int i;
cout << "Enter the String (Enter First Name) : ";
cin >> str;
for (i = 0; i <= strlen(str); i++) {
if (str[i] >= 97 && str[i] <= 122) //Why do we use this???
{
str[i] = str[i] - 32;
}
}
cout << "\nThe String in Uppercase = " << str;
getch();
}
【问题讨论】:
-
ASCII table 可能会对您有所帮助。
-
请不要从这个程序中学到任何东西,因为它很糟糕。它使用应该避免的magic numbers。不使用完美的
std::toupper函数。它依赖于 ASCII 编码,因此不可移植。而且不使用std::string,容易出现缓冲区溢出。 -
另外,
#include<string.h>自 90 年代以来已被弃用,#include<iostream.h>以及void main从来都不是合法的标准 C++。你应该得到更好和更新的代码来学习。 -
if(str[i]>=97 && str[i] 通常我们用(如果我们真的需要它,在现代 C++ 中很少出现这种情况)
if(str[i]>='a' && str[i]<='z'),因为它更具可读性。 -
@Veritasian 我看不出这怎么可能。你有没有使用双引号 (
") 而不是单引号 (')?
标签: c++ string lowercase toupper