编译时出现此错误:
$ gcc ArraysOfCharStrings1.cpp -lstdc++ -o ArraysOfCharStrings1
ArraysOfCharStrings1.cpp: In function 'char* int2month(int)':
ArraysOfCharStrings1.cpp:11: error: invalid conversion from 'const char' to 'char*'
ArraysOfCharStrings1.cpp:30: error: invalid conversion from 'const char*' to 'char*'
我正试图从一本书C ++中学习字符串数组的使用并使该程序有效:
#include <iostream>
#include <stdio.h>
// int2month() - return the name of the month
char* int2month(int nMonth)
{
// first check for a value out of range
if (nMonth < 1 || nMonth > 12)
{
const char* noGood = "invalid";
return noGood;
}
// nMonth is valid - return the name of the month
const char* pszMonths[] = {"invalid",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
return (pszMonths[nMonth]);
}
int main(int nArg, char* pszArgs[])
{
const char* response = int2month(1);
std::cout << response << "\n";
return 0;
}
我看到其他人回答并尝试了响应,但是我没有成功使程序运行。
答案 0 :(得分:0)
您正在尝试从char *函数返回const char *值
C:\Windows\System32\drivers\etc
如果将const放到函数中;
char* int2month(int nMonth)
{
if (nMonth < 1 || nMonth > 12)
{
const char* noGood = "invalid";
return noGood; //cannot return *char value
}
//other code
}
它将起作用