2016-08-03 177 views
2

我試圖將字符串中的字符從大寫轉換爲小寫。沒有編譯錯誤,但我仍然得到相同的輸出輸入:將大寫字母轉換爲小寫字母,反之亦然字符串

#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; 
} 
+0

所有的代碼可以用'C++'在一行中完成:#include ... std :: transform(a,a + strlen(a),a: :tolower);' – PaulMcKenzie

+0

@PaulMcKenzie:其實,沒有。這將'Ab'轉換爲'ab',但結果應該是'aB'。 – MSalters

回答

7

std::toupperstd::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; 
+0

我是新來這個雖然這解決了概率,但爲什麼我們用「的std ::」 我的意思是我一直在使用渦輪C++有我沒有使用過它曾經 –

+1

當你把「使用命名空間std;」沒有必要'std ::'。然而,這通常認爲是不好的行爲:HTTP://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice –

+3

@AshishChoudhary:麻煩的是,渦輪增壓C++是一個非常古老的C++編譯器,它預先約定了引入標準庫名稱空間的'std ::'標記的C++ 98標準。這不是一個好的C++編譯器。 –

1

你可以使用標準庫與返回給定字符的大寫或小寫字母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 !.你可以想象用小寫做同樣的事情

相關問題