gpt4 book ai didi

c++ - 将文件读入 C++ 中的字符串 vector 时,std::vector 下标超出范围

转载 作者:行者123 更新时间:2023-11-28 00:40:24 25 4
gpt4 key购买 nike

我是 C++ 新手。我学得很快,但我还不知道很多。

我看不到这个函数中索引的问题:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void get_rows(string filepath, vector<string> &rows);

int main() {
vector<string> rows;
get_rows("ninja.txt", rows);

for (int i = 0; i < rows.size(); i++) {
cout << rows[i] << endl;
}
}

void get_rows(string filepath, vector<string> &rows) {

ifstream file;
file.open(filepath);

string str;
int index = 0;

while (!file.eof()) {

getline(file, str);
rows[index] = str;
index++;
}
}

我们将不胜感激。

最佳答案

您构建了一个 std::vector<string> 对象:

vector<string> rows;

然后你试图访问它的元素,尽管这个 vector 中还没有元素:

rows[index] = str;

您应该使用 push_back 将新元素插入 vector 中方法:

rows.push_back(str);

另请注意,使用 while (!file.eof())错了因为getline可能会在循环内失败:

 while (!file.eof()) {
getline(file, str);
...
}

您的循环应如下所示:

 while (std::getline(file, str)) {
if (str.empty()) continue; // we skip empty lines
rows.push_back(str); // and push non-empty lines at the end
}

关于c++ - 将文件读入 C++ 中的字符串 vector 时,std::vector 下标超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19210352/

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