如果有人可以查看我的代码,我似乎无法找到它的问题,但我确信我只是不了解push_back / pop_back函数。
该程序旨在创建一个用户输入的向量,并在用户键入“停止”时停止。
肯定是pop_back给了我这个错误,但我不确定我做错了什么或如何改变它,任何帮助都表示赞赏。
代码:
#include <vector>
#include <string>
using namespace std;
int main(){
vector<string> animals;
vector<string> ages;
int const SIZE = 5;
string stopCheck = "stop";
string tempUserInput;
int i = 0;
//Loop used to gather user input and store it into array, animals and array, ages
cout << "Please enter up to 5 animal names and ages, or type 'stop' to end" << endl;
while( i<5 ) {
cout << i << endl;
// Taking user input for NAMES
cout << "Enter the name of an animal: ";
cin >> tempUserInput;
animals.push_back(tempUserInput);
cout << endl;
cout << animals.size() << endl;
//Function that automates the tolower function by applying it to each element automatically
//transform(animals[i].begin(), animals[i].end(), animals[i].begin(), tolower);
cout << animals.size() << endl;
//Checking for a stop input
if (!animals[i].compare(stopCheck)){
animals.pop_back();
i = 5;
}
i++;
return 0;
}
它没有正确地复制100%,但假设我的初始化是正确的,问题是while循环,我会感激任何帮助。
答案 0 :(得分:-2)
if (tempUserInput==stopCheck) { break; }
使用此行检查何时停止!
完整代码:
while( i<5 ) {
cout << i << endl;
// Taking user input for NAMES
cout << "Enter the name of an animal: ";
cin >> tempUserInput;
if (tempUserInput==stopCheck) { break; } //thats it !
animals.push_back(tempUserInput);
cout << endl;
cout << animals.size() << endl;
//Function that automates the tolower function by applying it to each element automatically
//transform(animals[i].begin(), animals[i].end(), animals[i].begin(), tolower);
cout << animals.size() << endl;
i++;
}