所以,我刚刚开始学习c++,我一直在看一些教程等。我写了一个小程序,应该像一个魔术八球一样,但是我在使用cin命令时遇到了一些问题。我写了 cin >> x; 其中 x 是一个字符串,当用户键入他们的问题时,程序应该打印一个随机响应。听起来很简单,但如果用户在问题中输入超过 1 个单词,则会打印超过 1 个响应。所以,如果我输入“我会活到 100 岁吗?” 我得到 6 个答案而不是 1 个。这是我的代码:(我敢肯定它可能很混乱,而且组织得不是很好,也不是以最有效的方式编码,就像我说的,我是初学者。)
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
string z = "Yes";
string b = "Signs point to yes";
string c = "It is certain";
string d = "It is decidedly so";
string e = "Without a doubt";
string f = "Yes, definitely";
string g = "You may rely on it";
string h = "As I see it yes";
string i = "Most likely";
string j = "Outlook good";
string k = "Reply hazy try again";
string l = "Ask again later";
string m = "Better not tell you now";
string n = "Cannot predict now";
string o = "Concentrate and ask again";
string p = "Don't count on it";
string q = "My reply is no";
string r = "My sources say no";
string s = "Outlook not so good";
string t = "Very doubtful";
string u;
int main()
{
srand(time(0));
cout << "Ask A Question" << endl << endl << "Type 'Exit' to end the program" << endl << endl;
int a = 1+(rand()% 20);
cin >> u;
if (u == "Exit"){
return 0;
}
if (u == "exit"){
return 0;
}
if (a == 1){
cout << z << endl << endl;
main();
}
if (a == 2){
cout << b << endl << endl;
main();
}
if (a == 3){
cout << c << endl << endl;
main();
}
if (a == 4){
cout << d << endl << endl;
main();
}
if (a == 5){
cout << e << endl << endl;
main();
}
if (a == 6){
cout << f << endl << endl;
main();
}
if (a == 7){
cout << g << endl << endl;
main();
}
if (a == 8){
cout << h << endl << endl;
main();
}
if (a == 9){
cout << i << endl << endl;
main();
}
if (a == 10){
cout << j << endl << endl;
main();
}
if (a == 11){
cout << k << endl << endl;
main();
}
if (a == 12){
cout << l << endl << endl;
main();
}
if (a == 13){
cout << m << endl << endl;
main();
}
if (a == 14){
cout << n << endl << endl;
main();
}
if (a == 15){
cout << o << endl << endl;
main();
}
if (a == 16){
cout << p << endl << endl;
main();
}
if (a == 17){
cout << q << endl << endl;
main();
}
if (a == 18){
cout << r << endl << endl;
main();
}
if (a == 19){
cout << s << endl << endl;
main();
}
if (a == 20){
cout << t << endl << endl;
main();
}
return 0;
}