如何根据输入向右或向左移动*?[C++]

How to move * to the right or left, based on input? [C++]

本文关键字:C++ 移动 何根 输入 左移      更新时间:2023-10-16

所以,我想写一个 c++ 程序,这样它就可以移动 *,根据用户输入,用户将能够根据需要多次向左或向右移动它。

cout << "*" << endl;
cout << Enter: l (Move Left) or r (Move Right): << endl;
cin >> c;
while (c == 'k' || c == 'l'){
  if(c == 'k'){

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

试试这个:

#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 enteredn" << 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):