简体   繁体   中英

C++ Template class to print string or int output based on the call from main function

Iam required to write a template class called Pattern which prints rows of int or strings based on the call from main function. RowInt and RowString are defined in the nontemplate class.

How to write RowInt, RowStr class and template class "Pattern" in a way that its able to recognise which row needs to be generated ie rows with string "*" or rows with int 1,2,3.... The sequence should be generated untill the number entered by user is met. ie if user enters 4, then it should print 1 2 3 4 for Pattern mypattern(number); and it should print **** for the call Pattern mypattern(number); Please suggest.

int main()
{
    int number = 0;

    do
    {
        cout << "Please input the number of rows (max 10:)" ;
        cin >> number;
    }
    while ((number < 1) || (number > 10))


    Pattern<RowStr> mypattern(number); //shows string * ,number of string will be equal to the number entered by the user
    Pattern<RowInt> mypattern(number);  //generates rows with numbers 1,2,3,4....untill the number entered by the user

Iam using Cygwin to run this program.

  class PatternString
  {
    private:
        typedef string strvalue;
        strvalue sstr;
    public:                                     
        PatternString(int num =0)   
        {

            for (int i = 1, k = 0; i <= num; ++i, k = 0)
            {
                for (int space = 1; space <= num - i; ++space)
                {
                    sstr += "  ";
                    cout<<"from firstloop"<< sstr<<endl;
                }
                while (k != 2 * i - 1)
                {
                    sstr += "X"; 
                    cout<<"from secondloop"<< sstr<<endl;
                    k++;
                }
            }
    }

    strvalue get_disc() const
    {
            return sstr;
    }
 };

is giving me an output of, pls. suggest where Iam going wrong.

X

 XXXX

   X  XXXXXXXX

     X    XXX  XXXXXXXXXXXX

       X      XXX    XXXXX  XXXXXXXXXXXXXXXX

I need an output star pyramid, to be generated one row at each call and storedin the string variable, this string variable will inturn be returned and stored in a linkedlist node

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