-
String Output Problem
How come the following c++ code generate nonsense character output?
#include <iostream.h>
char* mmString(int mm) {
char mmList[12][20] =
{ "January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December " };
return(mmList[mm-1]);
}
int main() {
int month;
for (month=1; month<13; month++) {
cout << mmString(month) << endl;
}
return 0;
}
The actual out put is 12 lines of nonsense character rather than the name of 12 months.
Why? Is it because I haven't initialize the string properly? If that is really the case, I cannot figure the rationale behind.
-
Sorry...
Problem solved. It is because char mmList[12][20] should be declared outside the function.
-
#include <iostream.h>
class getmonth {
public:
char mmList[12][20] =
{ "January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December " };
public:
char* mmString(int mm) const {
return(mmList[mm-1]);
}
};
int main() {
int month;
for (month=1; month<13; month++) {
cout << getmonth.mmString(month) << endl;
}
return 0;
}
This program generates error. I don't the mmList to be initialize at public part. How should I improve the program?
-
Code:
#include <iostream.h>
const char* mmString(int mm)
{
static char mmList[12][20] = { "January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December " };
return(mmList[mm-1]);
}
int main()
{
int month;
for (month=1; month<13; month++)
{
cout << mmString(month) << endl;
}
return 0;
}
Making the array static would be the easiest way.
You cannot initialize class member this way. You would have to strcpy all values in the constructor.