错误:从'char'到'const char*'的转换无效

error: invalid conversion from 'char' to 'const char*'

本文关键字:char 转换 无效 const 错误      更新时间:2023-10-16

我试着把所有的单词都转换成大写字母。这是标题:

#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]);
    }
}

main

中的定义如下
char Cadena[100];

在这里我使用它

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

错误信息是

错误:从'char'到'const char*'的转换无效

首先,你必须传递字符串的地址,所以你必须使用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;
}

我还编写了一个示例,您可以在这里执行和测试

TL;

  • 使用c风格字符串的演示
  • 使用std::string
  • 演示
<标题> 详细信息

因为我们主要讲英语,我要注意Mayusculas表示大写字母,cadena是一个序列或链——在这种情况下是一个c风格的字符串。

的呈现- c风格字符串

  1. int Mayusculas(char texto)应该是int Mayusculas(char *texto)

它需要是char *,因为您正在使用c风格的字符串,而不是单个字符。否则你就没有东西可以迭代了。

  • toupper()返回一个int,所以你应该强制转换,即改变
  • texto[liCount]=toupper(texto[liCount]);

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

  • 函数签名说你返回一个int,但你实际上没有返回任何东西。要么把它改成返回void,要么返回一些东西。(liCount,也许?)
  • 选择:std:: string

    但是你把这个问题标记为c++,那么为什么不使用std::string而不是C风格的字符串呢?它们更安全,更容易使用。

    引用Pierre从c++中将字符串转换为大写:

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

    这种方式将结果作为字符串返回。但如果你想像原来那样修改它,你可以这样做。看它在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;
    }
    

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

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