Reputation: 45
I'm new to C++ and I'm having trouble with this code:
string output_date(int day, int month, int year){
string date;
if ((day > 0 && day <= 30) && (month > 0 && month <= 12) && (year >= 2013)){
switch (month){
case 1: date = day + " JAN " + year; break;
case 2: date = day + " FEB " + year; break;
case 3: date = day + " MAR " + year; break;
case 4: date = day + " APR " + year; break;
case 5: date = day + " MAY " + year; break;
case 6: date = day + " JUN " + year; break;
case 7: date = day + " JUL " + year; break;
case 8: date = day + " AUG " + year; break;
case 9: date = day + " SEP " + year; break;
case 10: date = day + " OCT " + year; break;
case 11: date = day + " NOV " + year; break;
case 12: date = day + " DEC " + year; break;
}
}
return date;
}
when I try and do:
cout << output_date(22,12,2013);
nothing comes up. What am i doing wrong?
Upvotes: 0
Views: 128
Reputation: 1430
First thing you doing wrong is not using debugger.
Second thing you doing wrong is adding integers to string literal. For example, " DEC "
is a string literal which has pointer type char const *
. Result of expression
day + " DEC " + year
is a char const *
pointer pointing to unknown area of memory. In your case this unknown area was filled with zeroes, that's why you got empty string of type char const *
as result. (This was my case too, when I ran your program in debugger)
You assigned this empty string to data
, that's why you got empty output.
Upvotes: 0
Reputation: 20076
I would recommend using stringstream and returning a string from the stream:
stringstream date;
if ((day > 0 && day <= 30) && (month > 0 && month <= 12) && (year >= 2013)){
switch (month){
case 1: date << day << " JAN " << year; break;
case 2: date << day << " FEB " << year; break;
//yadda yadda.....
}
}
return date.str();
for this you need to include the header<sstream>
Upvotes: 5