将大写字母转换为小写字母,反之亦然字符串
我试图将字符串中的字符从大写转换为小写。没有编译错误,但我仍然得到相同的输出输入:将大写字母转换为小写字母,反之亦然字符串
#include <iostream>
#include<string.h>
#include<ctype.h>
using namespace std;
int main() {
char a[100];
cin>>a;
for(int i =0;a[i];i++){
if(islower(a[i])){
toupper(a[i]);
}
else if(isupper(a[i])){
tolower(a[i]);
}
}
cout<<a;
return 0;
}
std::toupper
,std::tolower
职能不到位的工作。他们返回的结果,所以你必须把它重新分配给a[i]
:
char a[100];
std::cin>>a;
for(std::size_t i =0;a[i];i++){
if(std::islower(a[i])){
a[i]=std::toupper(a[i]);// Here!
}
else if(std::isupper(a[i])){
a[i]=std::tolower(a[i]);// Here!
}
}
std::cout<<a;
我是新来这个虽然这解决了概率,但为什么我们用“的std ::” 我的意思是我一直在使用涡轮C++有我没有使用过它曾经 –
当你把“使用命名空间std;”没有必要'std ::'。然而,这通常认为是不好的行为:HTTP://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice –
@AshishChoudhary:麻烦的是,涡轮增压C++是一个非常古老的C++编译器,它预先约定了引入标准库名称空间的'std ::'标记的C++ 98标准。这不是一个好的C++编译器。 –
你可以使用标准库与返回给定字符的大写或小写字母lambda函数变换功能。
#include <algorithm>
#include <iostream>
using namespace std;
int main
{
string hello = "Hello World!";
transform(hello.begin(), hello.end(), hello.begin(), [](char c){
return toupper(c);})
cout << hello << endl;
}
这会输出HELLO WORLD !.你可以想象用小写做同样的事情
所有的代码可以用'C++'在一行中完成:#include ... std :: transform(a,a + strlen(a),a: :tolower);' –
PaulMcKenzie
@PaulMcKenzie:其实,没有。这将'Ab'转换为'ab',但结果应该是'aB'。 – MSalters