【问题标题】:String Pyramid with user input带有用户输入的字符串金字塔
【发布时间】:2020-06-07 04:26:30
【问题描述】:

我正在尝试读取字符串并将其输出为金字塔。我还不关心金字塔的形状,我只希望字符串正确输出。我在下面的示例代码中列出了我希望输出看起来如何的示例。如果能得到任何帮助,我将不胜感激,谢谢。

#include <iostream>
#include <string.h>
using namespace std;

//Letter Pyramid
//Ask user for input
//Use loops to display user input as pyramid
//User String "12345"
/*
      1
     121
    12321
   1234321
  123454321
*/

int main()
{
    //Store user input
    string user_input;
    string pyramid;
    string new_str;


    cout<< "Say Something"<<endl;

    getline(cin,user_input);
    cout<<endl;

    for(int i = 0; i <= user_input.length(); i++)
    {
         pyramid = user_input.substr(0,i);
         //cout<<pyramid<<endl;

         for(int j = user_input.length()-1; j >=0; j--)
         {
             new_str = pyramid + user_input[j];

             if(user_input[i] == ' ')
                {
                    user_input.erase(i,1);
                }
          }

                cout<<new_str<<endl;

      }



    return 0;
}

【问题讨论】:

    标签: c++ string loops for-loop


    【解决方案1】:

    我认为这段代码会产生您想要的结果。

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    //Letter Pyramid
    //Ask user for input
    //Use loops to display user input as pyramid
    //User String "12345"
    /*
          1
         121
        12321
       1234321
      123454321
    */
    
    int main()
    {
        //Store user input
        string user_input;
        string pyramid;
        string new_str;
    
    
        cout<< "Say Something"<<endl;
    
        getline(cin,user_input);
        cout<<endl;
    
        int ln = user_input.size() , mxLen = ln + ln - 1 ;
        for(int i = 1 ; i <= ln ; i ++) {
            // printing spaces
            for(int space = 1 ; space <= ln - i ; space ++) cout << ' ' ;
            // printing first half of string
            for(int ch = 0 ; ch < i ; ch ++) {
                cout << user_input[ch] ;
            }
            if(i >= 2) {
                // printing right sight of the string
                for(int ch = i - 2 ; ch >= 0 ; ch --) cout << user_input[ch] ;
            }
            cout << endl ;
        }
        return 0;
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多