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; } 

see: http://ideone.com/0x9amy

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

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -