2017-09-09 94 views
1

如果有人能够查看我的代码,我似乎无法找到它的问题,但我确信我只是不了解有关push_back/pop_back功能的内容。C++ 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循环我会很感激的任何帮助。

+1

那岂不是更容易做到这一点之前,* *'push_back'? if(tempUserInput == stopCheck){break; }' – rustyx

+0

你的调试器应该告诉你错误发生的地方。 “向量下标超出范围”意味着你做了一些类似'some_vector [index]'的地方,其中'index'>>'some_vector.size()',这意味着你访问了一个不存在的元素。 – nwp

+0

什么是你的问题? – Raindrop7

回答

-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++; 
}