string - Display a substring in c++ program -
here question: write program allows input integer represents month number (1 – 12) , program should display abbreviation corresponding month. example: if input 3, output should mar, march. hint: store month abbreviations in big string months = “janfebmaraprmayjunjulaugsepoctnovdec”
here codes far:
#include <iostream> using namespace std; int main() { int x; string months = "janfebmaraprmayjunjulaugsepoctnovdec"; cout << "enter integer between (1-12): " << endl; cin>>x; cout<<"\n"<<months.substr(x,3); return 0; }
problem: cannot figure out how corresponding abbreviations.
#include <iostream> using namespace std; int main() { int x; string months = "janfebmaraprmayjunjulaugsepoctnovdec"; cout << "enter integer between (1-12): " << endl; cin >> x; cout << months.substr((x-1)*3, 3); return 0; }
notes: should perform bounds check, otherwise might 'std::out_of_range'
also, there no benefit storing months this. use normal container instead:
string months[] = { "jan", /* , on */ };
Comments
Post a Comment