首页 > 解决方案 > 返回指令

问题描述

我正在用 C++ 编写一些代码,并且声明我是这种语言的新手。在实践中,在 if 中给出的指令之后,我写了一个字符串,指示用户编写一个新的输入。但是当它第二次插入变量时,程序停止了。你知道我该怎么做吗?啊,你也知道如何将字符添加到用户而不需要按回车吗?

#include <iostream>
using namespace std;

int main() {

  string line1 = "OOOOOO";
  string line2 = "OOIOOO";
  string line3 = "OOOOOO";
  string line4 = "OOOOOO";

  char I = 'I';
  char W = 'W';
  char A = 'A';
  char S = 'S';
  char D = 'D';

  char Input;

  cout << line1 << endl;
  cout << line2 << endl;
  cout << line3 << endl;
  cout << line4 << endl;

  cin >> Input;

  if (Input == D) {
    size_t found = line2.find(I);
    if (found != string::npos)
      line2[found] = 'O';
    line2[found + 1] = 'I';
    system("cls");

    cout << line1 << endl;
    cout << line2 << endl;
    cout << line3 << endl;
    cout << line4 << endl;
    cout << endl;

    cout << "x: " << found << endl;
    cin >> Input;
  }
  if (Input == A) {
    size_t found = line2.find(I);
    if (found != string::npos)
      line2[found] = 'O';
    line2[found - 1] = 'I';
    system("cls");

    cout << line1 << endl;
    cout << line2 << endl;
    cout << line3 << endl;
    cout << line4 << endl;
    cout << endl;

    cout << "x: " << found << endl;
    cin >> Input;
  }

  return 0;
}

标签: c++

解决方案


试试这个,我已经改变了你的 if to while。
现在当你的输入是'D'时会循环如果你在'D'之后输入'A',它将执行两个循环。

#include <iostream>
using namespace std;

int main() {

  string line1 = "OOOOOO";
  string line2 = "OOIOOO";
  string line3 = "OOOOOO";
  string line4 = "OOOOOO";

  char I = 'I';
  char W = 'W';
  char A = 'A';
  char S = 'S';
  char D = 'D';

  char Input;

  cout << line1 << endl;
  cout << line2 << endl;
  cout << line3 << endl;
  cout << line4 << endl;

  cin >> Input;

  while (Input == D) {
    size_t found = line2.find(I);
    if (found != string::npos)
      line2[found] = 'O';
    line2[found + 1] = 'I';
    system("cls");

    cout << line1 << endl;
    cout << line2 << endl;
    cout << line3 << endl;
    cout << line4 << endl;
    cout << endl;

    cout << "x: " << found << endl;
    cin >> Input;
  }

while (Input == A) {
    size_t found = line2.find(I);
    if (found != string::npos)
      line2[found] = 'O';
    line2[found - 1] = 'I';
    system("cls");
    cout << line1 << endl;
    cout << line2 << endl;
    cout << line3 << endl;
    cout << line4 << endl;
    cout << endl;

    cout << "x: " << found << endl;
    cin >> Input;
  }

  return 0;
}

推荐阅读