2012-02-28 52 views
0

出於某種原因,我不斷收到一個錯誤,指出「toupper不能用作函數」。但對於我的不足之處,toupper是一個將小寫字母轉換爲大寫字母的全局函數。獲取數組與Toupper一起工作

#include <cctype> 
#include <iostream>    
#include <string> 

using namespace std;     

int main() 

{ 


    string input; 
    string output; 
    int toupper; 

    cout<<"Enter a String of Charchters to be Capitalized : "; 
    cin>>input; 
    string arrayinput[20]= input; 
    output = toupper(arrayinput); 
    cout<<"\n\n\n"<<output<<"\n\n\n"; 



cout<<"Press <Enter> to Exit"; 
cin.ignore(); 
cin.get();  
return 0;       
} 
+0

'string arrayinput [20] = input'應該做什麼? – Naveen 2012-02-28 04:41:27

+0

接受輸入並將其製成數組 – kd7vdb 2012-02-28 04:42:55

+0

@ kd7vdb:這不是它的工作原理。你不能只接受一個'std :: string'並且「把它變成一個數組」。 – 2012-02-28 04:57:48

回答

3

您已經創建了一個名爲int toupper一個局部變量 - 重命名一個到別的東西。

修改添加: 還有更多的問題不僅僅是這個。 input是一個字符串;你想遍歷該字符串的長度,並使用string::at(i)在每個位置得到char*。然後使用atoi將char轉換爲int,這是toupper將其作爲參數的類型。

+0

我刪除了toupper變量,現在我得到了「從std :: string *'無效轉換爲」int「的錯誤,」does to upper必須是整數嗎? – kd7vdb 2012-02-28 04:45:46

+0

@ kd7vdb,不,只需重新命名/刪除toupper變量。它給你錯誤,因爲變量與函數本身具有相同的名稱。 – ddacot 2012-02-28 04:48:59

+0

據我所知,這是因爲您正在將數組的字符串(更具體地說是指向數組的第一個元素的指針)傳遞給該函數,所以您需要傳遞該數組的實際元素,例如, arrayinput [5] – 2012-02-28 04:49:36

1

如果你想這樣做一個字符串數組,然後固定在變量名發出後,在循環中使用std::transform

for (auto& str : arrayinput) 
    std::transform(std::begin(str), std::end(str), std::begin(str), ::toupper); 

或者,如果你沒有範圍爲基礎的有呢,你可以使用for_each

std::for_each(std::begin(arrayinput), std::end(arrayinput), [](string& str) { 
    std::transform(std::begin(str), std::end(str), std::begin(str), ::toupper); 
}); 
+0

上面我描述瞭如何將'string'轉換爲'toupper'使用的數據類型,但是如果你只需要使用'string',就像這裏那樣,那將是首選。 – tmpearce 2012-02-28 04:56:50

+0

@tmpearce不,'toupper'返回字符的ASCII碼,所以你不需要來回轉換。而使用'itoa'則是將數字'5'轉換爲字符串'「5」',這對於這種情況並不有用。 – 2012-02-28 04:58:46

+0

啊,你是對的。 (我不使用itoa或atoi - 去串!) – tmpearce 2012-02-28 05:00:04

0

您已經通過聲明一個變量具有相同名稱的功能引起了歧義。如前所述,只需更改變量的名稱即可解決問題。