错误:从'char'到'const char*'的转换无效
error: invalid conversion from 'char' to 'const 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]);
}
}
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风格字符串
-
int Mayusculas(char texto)
应该是int Mayusculas(char *texto)
它需要是char *
,因为您正在使用c风格的字符串,而不是单个字符。否则你就没有东西可以迭代了。
-
toupper()
返回一个int
,所以你应该强制转换,即改变 - 函数签名说你返回一个
int
,但你实际上没有返回任何东西。要么把它改成返回void,要么返回一些东西。(liCount
,也许?)
texto[liCount]=toupper(texto[liCount]);
texto[liCount] = (char)toupper(texto[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]);
}
}
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串