2014-01-29 51 views
-2

嗨,如何大寫字符數組C++

我已經看到了很多周圍的這個互聯網的職位,但我還是不明白怎麼做,完全是。出於某種原因,我只能大寫我的字符數組,直到有一個空間......

#include "stdafx.h" 
    #include <iostream> 
    #include <string> 


    std::string caps (char[]); 


    int main() { 
     const int MAXLEN = 256;  
     char chaine[ MAXLEN ] = ""; 

     //Here i am inputting my list of char into my array 
     std::cout << "Chaîne ? "; 
     std::cin >> chaine; 

     //Calling my caps function 
     caps(chaine); 

     // results 
     std::cout << "Résultat: " << chaine << std::endl; 

     _gettch(); 
     return 0; 


    } 


    std::string caps (char chaine []){ 


    std::string check=chaine; 

    for (int i=0; i<=check.length(); i++){ //I added check.length() because it's the only way I know to check for the length of the array 


    chaine[i]=toupper(chaine[i]); 

    } 

    return chaine; 

    } 

所以我們可以說我寫「嘿,你」的輸出將是「嘿」,就是這樣。我很困惑。謝謝您的幫助!

+4

這是因爲'std :: cin >> wtv;'停在空白處。你應該使用['getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline) – Borgleader

+0

只需看看'std :: cin >> chaine ;'。這會給你一個答案。附:至少你可以使用'gets'或它的類似物。 –

+2

或使用'std :: noskipws' – James

回答

1

您的輸入接收器改成這樣:

std::string chaine; 
    std::cout << "Chaîne ? "; 
    std::getline(std::cin, chaine); 

    caps(chaine);    // <-- pass the name by const reference 

這將不跳過空格工作。現在您已有std::string,而不是在caps內部創建另一個字符串,請將引用作爲參考傳遞,即將std::string caps (char chaine [])更改爲std::string caps (const std::string &chaine)

相關問題