我遇到的问题可能与代码块有关,但我只是想仔细检查一下,看看是否有人发现我的代码有问题。我已经认为它与 while 循环有关。我不断收到“Main.exe 已停止工作”错误。我个人在选择选项之间有很多困难,所以我试图制作一个快速而肮脏的 C++ 程序来在几个给定选项之间选择一个随机选项。这是我的代码:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
cout << "Enter Options to choose between." << endl << endl;
int i;
string option;
do {
cin >> option[i];
i++;
}
while (cin != "done");
cout << option[ rand() %i ];
}
最佳答案
这个程序(带有嵌入式注释)应该做你想做的事。
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::string;
using std::vector;
我使用了要从 std
命名空间导入的名称的显式列表,因为我不知道那里定义了哪些其他名称(可能超过 1000 个),而且我真的只需要这几个。
int main()
{
std::srand(std::time(NULL));
上面的语句初始化了随机数生成器,所以你不会在程序的每次运行中得到相同的“随机”数。
cout << "Enter options to choose between, an empty line to finish:\n";
我将您的 "done"
更改为一个空字符串,因为这样更容易输入。此外,此处不需要 std::endl
。您应该编写 "\n"
,它更短并且在大多数情况下是等效的。
vector<string> options;
这些是到目前为止已经输入的所有选项。每个选项都是一个string
,一个vector
可以容纳很多元素,所以这些是很多字符串。
for (string option; std::getline(cin, option) && option != ""; ) {
options.push_back(option);
}
此代码读取选项。变量 option
仅用于读取选项。之后,就不再需要它了。 for
循环会自动限制option
变量的范围,使其只能在for
循环中使用。
我还将 cin >> option
更改为 getline(cin, option)
以允许包含空格的选项。
cout << "You entered the following options:\n";
for (std::size_t i = 0; i < options.size(); i++) {
cout << "* " << options[i] << "\n";
}
cout << "Your random option is " << options[std::rand() % options.size()] << "\n";
}
关于c++ - 用极其简单的代码悲伤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578224/