目前我正在编写C ++小型游戏机游戏,我遇到了问题。问题的实质是我不能一个回一个循环。
这是我的代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
Main:
for (int i = 0; i < 200; i++) {
vector <string> v;
vector <char> v1;
string word;
cin >> word;
char lastChar = word.at(word.length() - 1);
cout << "Word's last character is:" << lastChar << endl;
char firstChar1 = word[0];
//v.push_back(word);
if (i == 1) {
v1.push_back(lastChar);
v1.push_back(firstChar1);
}
string word1;
cin >> word1;
char firstChar = word1[0];
cout << "Word's first character is:" << firstChar << endl;
if (i==1) v1.push_back(firstChar);
char lastChar1 = word1.at(word1.length() - 1);
v1.push_back(lastChar1);
//Checking:
if (lastChar != firstChar) {
cout << "Game stopped" << endl;
//cout << "Your score is " << wordcounter << endl;
break;
}
}
system("pause");
return 0;
}
我希望用户必须输入以前一个单词的最后一个字母开头的单词,例如“deer”。然后,一个单词以“r”字母等开头。我的代码只适用于两个单词。当我输入第三个单词时,它再次启动循环并且没有查看前一个单词。
当前输出:
deer
Word's last character is:r
rabbit
Word's first character is:r
Ball
Word's last character is:l
当我输入球时,工作代码将写入游戏停止。但不幸的是,我的代码错了。
请帮助,
感谢。
答案 0 :(得分:0)
如果if(lastChar != firstChar)
失败,则应将lastChar
设置为word1
lastChar,并在下一次迭代中进行检查。编辑的代码在这里:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
char lastChar;
for (int i = 0; i < 200; i++) {
vector <string> v;
vector <char> v1;
string word;
cin >> word;
char firstChar1 = word[0];
if (i >= 1){ //check in 2nd iteraion and so on iteration.
if (lastChar != firstChar1)
break;
}
lastChar = word.at(word.length() - 1);
cout << "Word's last character is:" << lastChar << endl;
//v.push_back(word);
if (i == 1) {
v1.push_back(lastChar);
v1.push_back(firstChar1);
}
string word1;
cin >> word1;
char firstChar = word1[0];
cout << "Word's first character is:" << firstChar << endl;
if (i == 1) v1.push_back(firstChar);
char lastChar1 = word1.at(word1.length() - 1);
v1.push_back(lastChar1);
//Checking:
if (lastChar != firstChar) {
break;
}
lastChar = word1.at(word1.length() - 1); //new line added.
}
cout << "Game stopped" << endl;
//cout << "Your score is " << wordcounter << endl;
return 0;
}