gpt4 book ai didi

c++ - 将文件写入二维数组

转载 作者:行者123 更新时间:2023-11-28 03:15:50 24 4
gpt4 key购买 nike

我成功编写了代码,将包含文本数据的 .dat 文件写入一维数组。然而,当我尝试开发我的代码以将这些文件写入二维数组时,我一直陷入指针问题。以下代码是我要修复的内容:

while (getline(fin, line)) {
char* buf = _strdup(line.c_str());
// parse the line into blank-delimited tokens
int n = 0; // a for-loop index
int s = 0;
int m = 0;
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE][MAX_TOKENS_PER_LINE] = {};
char *next_token;
// parse the line
token[0][0] = strtok_s(buf, DELIMITER, &next_token); // first token
//token[0] = strtok(buf, DELIMITER); // first token
if (token[0][0]) {
// zero if line is blank
for (n = 1; n < MAX_TOKENS_PER_LINE; n++) {
token[m][n] = strtok_s(0, DELIMITER, &next_token);
//token[n] = strtok(0, DELIMITER);
if (!token[m][n]) break; // no more tokens
m++;
}
}
// process (print) the tokens
for (int i = 0; i < n; i++) // n = #of tokens
for (int j = 0; j<m; j++) {
cout << "Token[" << i << "," << j << "] = " << token[i][j] << endl;
cout << endl;
}
fin.clear();
fin.close();
free(buf);
}

显然在第一行之后,第一个标记 token[0][0] 将指向垃圾,因为不同的数据将在 buf 中。如何避免这个问题?

最佳答案

更好的解决方案可能是也使用 std::istringstreamstd::getline 进行分词:

std::vector<std::vector<std::string>> tokens;

int current_line = 0;
std::string line;
while (std::getline(fin, line))
{
// Create an empty vector for this line
tokens.push_back(std::vector<std::string>());

std::istringstream is(line);

std::string token;
while (std::getline(is, token, DELIMITER))
tokens[current_line].push_back(token);

current_line++;
}

在此之后,tokens 将在文件中每行包含一个条目,并且每个条目将是一个(可能为空的) token vector 。

关于c++ - 将文件写入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881057/

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