简体   繁体   中英

Display a substring in c++ program

Here is the question: Write a program that allows as input an integer that represents a month number (1 – 12) and the program should display the abbreviation for the corresponding month. Example: If the input is 3, then the output should be Mar, for March. Hint: Store all the month abbreviations in a big string months = “JanFebMarAprMayJunJulAugSepOctNovDec”

here are my codes so far:

#include <iostream>

using namespace std;

int main()
{
    int x;
    string months = "JanFebMarAprMayJunJulAugSepOctNovDec";

    cout << "Enter an integer between (1-12): " << endl;
    cin>>x;

    cout<<"\n"<<months.substr(x,3);
    return 0;
}

problem: cannot figure out how to get the corresponding abbreviations.

#include <iostream>

using namespace std;

int main()
{
    int x;
    string months = "JanFebMarAprMayJunJulAugSepOctNovDec";

    cout << "Enter an integer between (1-12): " << endl;

    cin >> x;

    cout << months.substr((x-1)*3, 3);
    return 0;
}

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

Notes: You should perform bounds check, otherwise you might get 'std::out_of_range'

Also, there is no benefit from storing months like this. Use normal container instead:

string months[] = { "Jan", /* and so on */ };

You were almost there:

const auto n = 3*(x-1);
const auto &abbr = months.substr(n, 3);
std::cout << abbr << std::endl;

Which part didn't you get? The fact that C++ is zero-based?

You should specify the starting character that matches the month you are dealing with, ie:

months.substr( 3*(x-1), 3 );

Anyway, this is not the better way to proceed. For you purpose, you should better use an array, this way:

const char* month[] = { "Jan", "Feb", ... };
...
cout << month[x-1] << std::endl;

To "display a substring" you don't literally have to create a string temporary with substr . Instead, you can write directly to std::cout ; just pass in a pointer to the first character to print (ie &months[(x - 1) * 3] ), and the number of characters to print:

#include <iostream>
#include <string>
#include <cassert>

using namespace std;

int main()
{
    const string months = "JanFebMarAprMayJunJulAugSepOctNovDec";

    cout << "Enter an integer between (1-12): \n";

    int x;
    if (cin >> x && 1 <= x && x <= 12)
        (cout << '\n').write(&months[(x - 1) * 3], 3);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM