错误:来自' char'的无效转换到#char; char *'

时间:2015-10-11 04:33:56

标签: c++ char

我试图将所有单词转换为大写字母。这是标题:

#include <string.h>
#include <ctype.h>

using namespace std;

int Mayusculas(char texto)
{
    int liCount;
    for(liCount=0;liCount<strlen(texto);liCount++)
    {
        texto[liCount]=toupper(texto[liCount]);
    }
}

这是主要

中的定义
char Cadena[100];

这是我使用它的地方

case 1:
    Mayusculas(Cadena);
    cout<<Cadena<<endl;

错误消息是

  

错误:来自&#39; char&#39;的转换无效to&#39; const char *&#39;

3 个答案:

答案 0 :(得分:0)

TL; DR:

详细

由于我们主要讲英语,我会注意到Mayusculas表示大写字母,cadena是一个系列或链 - 在这种情况下是C风格的字符串。

如同呈现 - C风格的弦乐

  1. int Mayusculas(char texto)应为int Mayusculas(char *texto)
  2. 它需要是char *,因为您使用的是C风格的字符串,而不是单个字符。否则你没有什么可以迭代的。

    1. toupper()会返回int,因此您应该进行投射,即更改
    2. texto[liCount]=toupper(texto[liCount]);

      texto[liCount] = (char)toupper(texto[liCount]);

      1. 函数签名表示您正在返回int,但实际上并未返回任何内容。所以要么改变它以返回void,要么返回一些东西。 (liCount,也许?)
      2. 替代方案:std :: string

        但是您将此问题标记为C ++,那么为什么不使用std::string而不是C风格的字符串?它们更安全,更易于使用。

        Convert a String In C++ To Upper Case引用皮埃尔:

        #include <algorithm>
        #include <string>
        
        std::string str = "Hello World";
        std::transform(str.begin(), str.end(),str.begin(), ::toupper);
        

        或者如果您仍然想要自己的功能,

        #include <algorithm>
        #include <string>
        #include <iostream>
        
        using namespace std;
        
        string Mayusculas(std::string str)
        {
            transform(str.begin(), str.end(), str.begin(), ::toupper);
            return str;
        }
        
        int main()
        {
            string Cadena = "Hola al Mundo";
            cout << Mayusculas(Cadena) << endl;
            return 0;
        }
        

        这样可以将结果作为字符串返回。但是如果你想像原版一样修改它,你可以这样做。看到它工作at Ideone

        void Mayusculas(std::string & str) // reference parameter
        {
            transform(str.begin(), str.end(), str.begin(), ::toupper);
        }
        
        int main()
        {
            string Cadena = "Hola al Mundo";
            Mayusculas(Cadena);
            cout << Cadena << endl;
            return 0;
        }
        

答案 1 :(得分:0)

首先,您必须传递字符串的地址,因此您必须在函数中使用char而不是char*

void Mayusculas(char *text)
{
    for(int post = 0; pos < std::strlen(text); pos++)
    {
        text[post] = (char) toupper(text[pos]);
    }
}

注意: char *text表示字符串中第一个字符的地址。

main函数中的定义很好,因此您可以像这样使用它:

int main() {
  // ...
  char Cadena[100];
  Mayusculas(Cadena);

  std::cout << Cadena << std::endl;
  return 0;
}

我还写了一个例子,你可以执行并测试here

答案 2 :(得分:-1)

将您的代码更改为:因为int可能不适合接收器类型char

int Mayusculas(char *texto)
{
    int liCount;
    for(liCount=0;liCount<strlen(texto);liCount++)
    {
        texto[liCount]= (char) toupper(texto[liCount]);
    }
}