我正在制作一个名叫吉尔伯特的机器人,他充满了愚蠢.到目前为止.
http://pastecode.org/index.php/view/36572371
让我们说他回答了一个问题,然后就会说
"问别人?(是/否)"
如果我说Y,它会说
"问别人?(是/否)"
再次.说Y再问你一次.我该如何解决?
// Created by Brad Gainsburg on 4/23/13.
// Copyright (c) 2013 Ostrich. All rights reserved.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char* argv[]) {
cout << " _____ _ _ _ _ " << endl;
cout << " / ____(_) | | | | " << endl;
cout << "| | __ _| | |__ ___ _ __| |_ " << endl;
cout << "| | |_ | | | '_ \\ / _ \\ '__| __|" << endl;
cout << "| |__| | | | |_) | __/ | | |_ " << endl;
cout << " \\_____|_|_|_.__/ \\___|_| \\__|" << endl;
//Ask Question
char loop;
do {
string sentence;
string search;
size_t pos;
int count;
cout << "Ask Gilbert a question:" << endl;
getline(cin, sentence);
//Words
count = 0;
search = "apple";
pos = sentence.find(search);
if (pos != string::npos && count == 0) {
cout << "i likez thouse.";
++count;
}
count = 0;
search = "pear";
pos = sentence.find(search);
if (pos != string::npos && count == 0) {
cout << "i likez thou.";
++count;
}
//End Loop
cout << endl << "Ask another?(Y/N)" << endl;
cin >> loop;
cout << string(3, '\n');
} while (loop == 'y' || loop == 'Y');
if (loop == 'n') {
cout << "i didnt like you anyways...";
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
问题出在以下声明中:
cin >> loop;
Run Code Online (Sandbox Code Playgroud)
例如'y',当用户输入一个字母时,按回车键.它实际上会在输入缓冲区中存储两个字符,'y'并且'\n'.角色'y'存储在loop,但'\n'遗体.因此,当内部do-while循环到达此行时:
getline (cin, sentence);
Run Code Online (Sandbox Code Playgroud)
由于\n缓冲区中已有一个字符,因此getline会接受它,并且不会要求用户输入更多字符.因此,你看到了奇怪的提示输出.
请尝试以下方法:
cin >> loop;
cin.ignore();
Run Code Online (Sandbox Code Playgroud)
通过上述更改,它应该按预期工作.