【问题标题】:How to move * to the right or left, based on input? [C++]如何根据输入将 * 向右或向左移动? [C++]
【发布时间】:2014-03-05 06:52:41
【问题描述】:

所以,我想写一个c++程序,让它可以移动*,根据用户的输入,用户可以向左或向右移动任意多次。

cout << "*" << endl;
cout << Enter: l (Move Left) or r (Move Right): << endl;
cin >> c;

while (c == 'k' || c == 'l'){
  if(c == 'k'){

这就是我目前所拥有的,我不知道如何继续。 提前感谢您的任何建议/帮助。

【问题讨论】:

    标签: c++


    【解决方案1】:

    试试这个:

    #include <iostream>
    
    using namespace std;
    
    int main() 
    {
        char c='x';
        int position = 0; //starts from the left most position
        int temp =0;
        cout << "*" << endl;
        cout << "Enter: l (Move Left) or r (Move Right) or x (exit): " << endl;
        cin >> c;
    
    while (c != 'x')
    {
        if((c == 'r')||(c=='l'))
        {
            if(c == 'r')
            {
            position++;
            }
            else if(c == 'l')
            {
            if(position==0) 
                position=0;
            else
                position--;
            }
            temp=position;
            while(temp--!=0)
            {
            cout << " "; //print space
            }
            cout << "*" <<endl;
        }   
        else
        {
            cout << "Wrong character entered\n" << endl;
        }
        cout << "Enter: l (Move Left) or r (Move Right) or x (exit): "<< endl;
        cin >> c;
    }
    return 0;
    

    }

    输入:

    rrrrrrrlllx
    

    输出:

    *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
     *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
      *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
       *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
        *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
         *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
          *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
           *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
          *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
         *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
        *
    Enter: l (Move Left) or r (Move Right) or x (exit): 
    

    【讨论】:

    • 如何移动超过 2 个或更多的东西?
    • 嗯,你的问题和你提供的输入类型,没有要求它。对于您所询问的内容,您需要输入lr 多次,以使其向左或向右移动
    • 哦,对不起,澄清一下。如果我想再次使用这个程序,你如何移动两个或更多的东西例如要制作一个形状[三角形或正方形],你怎么能移动整个东西?
    • 为此,您可以从用户那里获取两个输入:1) lr 2) 您要移动多少个位置。在第二种情况下,添加/减去编号。相应地,来自上述代码中position 变量的位置。
    • 希望我回答了你的问题。
    猜你喜欢
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2019-04-06
    • 2016-07-31
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多