2012-02-28 54 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

您已经通过声明一个变量具有相同名称的功能引起了歧义。如前所述,只需更改变量的名称即可解决问题。