gpt4 book ai didi

c++ - 我的程序返回错误 "vector subscript out of range."

转载 作者:行者123 更新时间:2023-11-28 02:10:55 26 4
gpt4 key购买 nike

我不确定是哪个 vector 导致了错误,也不确定问题出在哪里。我正在尝试从文件中输入姓名和生日,并将它们设置为等于 vector 中的一部分。文件是:

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

由于错误,我什至不确定我的代码是否完成了此操作。我尝试阅读更多关于 stringstream 的内容,但我不明白如何正确实现它。如果需要可以提供提到的日期类,但它很长。非常感谢任何有关改进程序以及问题发生原因的意见。这是我的代码:

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

再次感谢:]

最佳答案

People[i].name[i] = input;在for循环中,People[i].name仍然是一个空 vector ,调用operator[] 将是 UB。您可以提前调整它们的大小,或者使用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

关于c++ - 我的程序返回错误 "vector subscript out of range.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com