-10 c++
如果我输入5,我希望它显示"May",但他们显示的是始终警告,我怎样才能使它工作?
#include <iostream>
using namespace std;
int main() {
int month;
char *m_name[] = {" ", "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
cout << "Enter month: ";
cin >> month;
if (month >= 1 && month <= 12)
cout << m_name[month];
else cout << "Illegal month";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器警告:
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
^
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
main.cpp:8:70: warning: ISO C++ forbids converting a string constant to 'char*' [-Wpedantic]
Run Code Online (Sandbox Code Playgroud)
警告可能是因为char*.将其更改为char const*.
说明:字符串文字具有类型char const[N],其中N字符串中的字符数为+ 1,最后为NUL.通常,此类型的数组只能转换为char const*,但是存在一个特殊规则,允许将字符串文字转换char*为C兼容性.这是一种不安全的转换,因此编译器会对此发出警告.