没有从“const char”到“int” [英] No conversion from "const char" to "int"
本文介绍了没有从“const char”到“int”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是问题代码。
#include< iostream>
#include< cctype>
using namespace std;
void convertToUppercase(char *);
int main()
{
char phrase [] =字符和$ 32.98;
cout<< 转换之前的短语是:<短语;
convertToUppercase(phrase);
cout<< \\\
转换后的短语是:<短语<< endl;
return 0;
}
void convertToUppercase(char * sPtr)
{
while(* sPtr!=\0)
{
if(islower(* sPtr))
* sPtr = toupper(* sPtr);
cout<< sPtr(before)=<< sPtr;
sPtr ++;
cout<< \\\
sPtr(after)=<< sPtr < endl;
}
}
输出窗口显示:
1> d:\sync files\将小写字母转换为大写字母\转换小写字母到大写字母\main.cpp 19):error C2446:'!=':没有从'const char *'到'int'的转换
1>没有可能进行此转换的上下文
1> d:\sync files \将小写字母转换为大写字母\转换小写字母到大写字母\main.cpp(19):错误C2040: '!=':'int'不同于'const char [2]'的间接级别
我犯了什么错误?我已经完全从我的书复制代码,但问题仍然存在。对不起,我找不到。
解决方案
- 您的while条件应该检查
* sPTR!='\0'
,\0
的类型为const char *
- 如果
toupper
传递了一个负值,则调用UB,因此请务必使用static_cast< unsigned char> / code>(详细信息 a>)
- 您不需要检查
islower
,toupper
-
使您的生活更轻松,使用
std :: string
:void convertToUpper(std :: string& str){
for(auto& v:str)
v = toupper(static_cast< unsigned char& v));
}
The following is the problem code.
#include <iostream>
#include <cctype>
using namespace std;
void convertToUppercase(char *);
int main()
{
char phrase[] = "characters and $32.98";
cout << "The phrase before conversion is : " << phrase;
convertToUppercase(phrase);
cout << "\nThe phrase after conversion is : " << phrase << endl;
return 0;
}
void convertToUppercase(char *sPtr)
{
while (*sPtr != "\0")
{
if (islower(*sPtr))
*sPtr = toupper(*sPtr);
cout << "sPtr (before) = " << sPtr;
sPtr++;
cout << "\nsPtr (after) = " << sPtr << endl;
}
}
The output window shows me that :
1>d:\sync files\converting lowercase letter to uppercase letters\converting lowercase letter to uppercase letters\main.cpp(19): error C2446: '!=' : no conversion from 'const char *' to 'int'
1> There is no context in which this conversion is possible
1>d:\sync files\converting lowercase letter to uppercase letters\converting lowercase letter to uppercase letters\main.cpp(19): error C2040: '!=' : 'int' differs in levels of indirection from 'const char [2]'
Where is the mistake I made? I have exactly copied the code from my book but the problem still exist. Sorry, I cannot find it out. need Help.
Thank you for your attention
解决方案
- Your while condition should check
*sPTR != '\0'
,"\0"
is of typeconst char*
- If
toupper
is passed a negative value, you invoke UB, so make sure to call it withstatic_cast<unsigned char>
(Details) - You do not need to check
islower
,toupper
already does that Make your life easier, use
std::string
:void convertToUpper (std::string& str) { for (auto& v:str) v = toupper(static_cast<unsigned char>(v)); }
这篇关于没有从“const char”到“int”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文