程序在C ++中打印以下模式

时间:2016-05-11 09:29:58

标签: c++

考虑到输入有奇数位,如何在C ++中生成以下模式。

P         M
 R      A
   O  R
     G
  O    R
 R       A
P          M 

我尝试了以下代码,但我不知道如何继续使用它。

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char word[100];
    int len, temp;
    cout << "Input word with odd letters: \n";
    cin >> word;
    len = strlen(word);
    cout << "Entered word was : "<< word << " and of size: " << strlen(word) << "\n";
    if(len % 2==0)
    {
        cout << "Please enter a word with odd number of letters!";
    }
    else
    {
        int mid;
        mid = (len - 1)/2;
        cout << "The middle number is : " << mid+1 << " and character is " << word[mid] << "\n";
        temp = len - 1;
        for(int i=0; i<len; i++)
        {
            // Some logic to display it just like above
        }
        cout << "done" << endl;
    }
}

1 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <cstring>
using namespace std;

void printSpace(int n)
{
    for(int i=0; i<n; i++)
    {
        cout << "  ";
    }
}

int main()
{
    char word[100];
    int len, temp;
    cout << "Input word with odd letters: \n";
    cin >> word;
    len = strlen(word);
    cout << "Entered word was : "<< word << " and of size: " << strlen(word) << "\n";
    if(len % 2==0)
    {
        cout << "Please enter a word with odd number of letters!";
    }
    else
    {
        int mid;
        mid = (len - 1)/2;
        cout << "The middle number is : " << mid+1 << " and character is " << word[mid] << "\n";
        temp = len - 1;

        int up=len-2, side=0, down=1;
        char a,b;
        for(int i=0; i<len; i++)
        {
            if(i < mid)
            {
                a = word[i];
                b = word[len-i-1];
            }
            else
            {
                a = word[len-i-1];
                b = word[i];
            }

            printSpace(side);

            cout << a;

            if(i < mid)
            {
                printSpace(up);
                up -= 2;
            }
            else if(i > mid)
            {
                printSpace(down);
                down += 2;
            }

            if(i != mid) cout << b;

            printSpace(side);
            cout << endl;

            if(i < mid) side++;
            else side--;
        }
        cout << "done" << endl;
    }
}