我遇到的问题可能是代码块的问题,但我只想再次检查一下,看看是否有人发现了我的代码的问题。我已经认为这与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 ];
}发布于 2014-10-26 21:57:06
这个程序(带有内嵌的注释)应该能做你想做的事情。
#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";
}发布于 2014-10-26 21:38:49
您正在使用每个cin,而不是字符来读取字符串,因此您的字符串不是您想要使用的。
std::vector<std::string> options;
...
string in;
cin >> in;
options.push_back(in);所以这里用一个字符串向量代替一个字符串,然后用字符串填充它。
https://stackoverflow.com/questions/26578224
复制相似问题