c++ - 返回指令
问题描述
我正在用 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;
}
解决方案
试试这个,我已经改变了你的 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;
}
推荐阅读
- javascript - PHP 和 JavaScript 中后缀运算符 (x++) 的不同结果
- java - 如果有几行,java,selenium,如何在xpath中制作参数并使代码更易于阅读
- python - 基于更高优先级的文件列表转换
- cupy - 在 C/C++ 中公开 CUPY MemoryPointer 的好方法?
- android - onCreateInputConnection 为 SearchView 返回 null
- sql-server - 如何自动启动 SQL Server 作业
- docker - 使用 IP 地址而不是 localhost 或 127.0.0.1 的本地 Docker Registry
- arduino - 如何使用 Arduino HTTPClient 发布图像
- python - Prometheus Metrics 中究竟做了什么(例如直方图)
- r - 使用 ggplot 将两种不同类型的图组合到一个窗口中