我的程序返回错误“向量下标超出范围”。

时间:2016-03-01 01:38:50

标签: c++

我不确定哪个向量导致错误或问题来自何处。我正在尝试从文件中输入名称和生日,并将它们设置为等于向量中的一部分。该文件是:

Mark,12/21/1992
Jay,9/29/1974
Amy Lynn,3/17/2010
Bill,12/18/1985
Julie,7/10/1980
Debbie,5/21/1976
Paul,1/3/2001
Ian,2/29/1980
Josh,10/31/2003
Karen,8/24/2011

由于错误,我甚至不确定我的代码是否能完成此操作。我尝试阅读更多字符串流,但我不明白如何正确实现它。如果需要,可以提供所提到的日期类,但它很长。关于改进计划以及问题发生原因的任何意见都非常感谢。 这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "c://cpp/classes/Date.cpp"
using namespace std;

struct person {
    vector<string> name; // One name string vector
    vector<Date> birthdate; // One birthdate vector
    vector<Date> birthday; // birthday vector
};

int main() {
    string input, input2; // Two string inputs
    const int PEOPLE_NUM = 10; // Amount of people

    vector<person> People(PEOPLE_NUM); // Define vector called People with 10 positions
    string test;
    ifstream inputFile("C:/Users/Taaha/Documents/CMSC226/Project 3/Names.txt", ios::in);
    for (int i = 0; i < PEOPLE_NUM; i++) {
        getline(inputFile, input, ','); // input the line, stop when a comma
        People[i].name[i] = input; // Add input into the vector 
        getline(inputFile, input2, ',');
        People[i].birthdate[i] = input2;
        cout << i;
    }
    inputFile.close(); // close file

    Date birthday;
    for (int i = 0; i < PEOPLE_NUM; i++) {
        Date birthday(People[i].birthday[i].getDay(), People[i].birthday[i].getMonth(), Date().getYear());
        People[i].birthday[i] = birthday;
    } // Not finished yet, but turns birthdate into birthday
    return 0;
}

再次感谢:]

1 个答案:

答案 0 :(得分:2)

在for循环中People[i].name[i] = input;People[i].name仍为空向量时,在其上调用operator[]将为UB。您可以提前resize,或使用push_back

for (int i = 0; i < PEOPLE_NUM; i++) {
    getline(inputFile, input, ',');
    People[i].name[i] = input;        // People[i].name is still empty here 
    getline(inputFile, input2, ',');
    People[i].birthdate[i] = input2;  // People[i].birthdate is still empty here
    cout << i;
}

您可以使用push_back,例如

for (int i = 0; i < PEOPLE_NUM; i++) {
    getline(inputFile, input, ',');
    People[i].name.push_back(input); 
    //            ~~~~~~~~~~
    getline(inputFile, input2, ',');
    People[i].birthdate.push_back(input2);
    //                 ~~~~~~~~~~
    cout << i;
}

对于另一个for循环也是如此。

for (int i = 0; i < PEOPLE_NUM; i++) {
    Date birthday(People[i].birthdate[i].getDay(), People[i].birthdate[i].getMonth(), Date().getYear());  // typo of birthdate?
    //                      ~~~~~~~~~                        ~~~~~~~~~
    People[i].birthday.push_back(birthday);
    //                 ~~~~~~~~~~
} // Not finished yet, but turns birthdate into birthday