I have a function which is supposed to write all the data from a txt file to a vector, and it comes up with the error, "Debug assertion failed. C++ vector subscript out of range". I'm not too sure why this is happening. I decided to do this because the file is an unknown size. If there is a better way to do this, that would help. Or, if there is an error, it would be good to know, thanks.
void getUserPassData() {
int count = 1;
cout << "Loading...\n";
ifstream userInFile;
ifstream passInFile;
userInFile.open("data\\usernameList.txt"); //Opens the username file
passInFile.open("data\\passwordList.txt"); //Opens the password file
//Cycles through the files, putting them into an array
while (!userInFile.eof()) {
for (int i = 0; i < count; ++i) {
userInFile >> usernames[i];
passInFile >> passwords[i];
}
++count;
}
userInFile.close();
passInFile.close();
}
So I believe I fixed that error, but now I have a new one. Its not a compiler error, just that the code isn't doing what I want. It seems that I implemented the .eof() function wrong, or I just do not understand the logic of it, because I included some "Loading..." tests to see whether it makes it through the function, and it just infinitely loops. Heres the current status of the code.
void getUserPassData() {
int count = 1;
cout << "Loading...\n";
ifstream userInFile;
ifstream passInFile;
userInFile.open("data\\usernameList.txt"); //Opens the username file
passInFile.open("data\\passwordList.txt"); //Opens the password file
//Cycles through the files, putting them into an array
//Two count variables save memory by eliminating the need to pass through all prior lines in for loop
while (userInFile.eof() == false) {
for (int i = 0; i < count; ++i) {
usernames.resize(usernames.size() + 1);
passwords.resize(passwords.size() + 1);
getline(userInFile, usernames[i]);
getline(passInFile, passwords[i]);
cout << "Loading...";
}
++count;
}
userInFile.close();
passInFile.close();
cout << "Successfully loaded vector data...";
}
usernames and passwords are not defined within the function but I'm guessing they're std::vector<std::string> and that the input file has username and password on alternate lines? Rather than manage two vectors it'd be far easier to use a struct with appropriate overloads of the ctor (and insertion << operator).
Here you can also reserve vector capacity before starting the file read to avoid interim re-allocations: