读取字符串文本输入以创建 2D 矢量

reading string text input to create a 2D Vector

本文关键字:创建 2D 矢量 输入 字符串 文本 读取      更新时间:2023-10-16

给定一个常规文本文件:

56789
28385
43285
22354
34255

我正在尝试读取文本文件中的每个字符串字符并将它们存储在 2D 矢量中。

首先,我想取每个字符串行。然后我想将行中的每个字符转换为 int,然后push_back到行中。然后我想重复每一行。

在我的 2D 向量中输出每一列和每一行时,我想要相同的确切输出:

56789 //each number an int now instead of a string
28385
43285
22354
34255

我的问题是我尝试使用给出错误的i = stoi(j);

No matching function for call to 'stoi'

我确实有正确的#include能够使用stoi()

vector<vector<int>> read_file(const string &filename) 
{
string file, line; stringstream convert; int int_convert, counter;
vector<vector<int>> dot_vector;
file = filename;
ifstream in_file;
in_file.open(file);
while (getline(in_file, line)) {
counter++; //how many lines in the file
}
char current_char;
while (getline(in_file, line)) {
for (int i = 0; i < counter; i++) {
vector<int> dot_row;
for (int j = 0; j < line.size(); j++) {
current_char = line[j];
i = stoi(j); //this is giving me an error
dot_row.push_back(i);
}
dot_vector.push_back(dot_row);
}
}
in_file.close();
return dot_vector;
}

这里

i = stoi(j);
// j is integer already

标准::斯托伊 期望一个字符串作为参数,而您提供的是一个int

您可以将字符转换为字符串并调用std::stoi

如下所示
std::string CharString(1, line[j]);
dot_row.emplace_back(std::stoi(CharString));

或者可以直接将字符转换为 int,同时保留向量:

dot_row.emplace_back(static_cast<int>(line[j] - '0'));

您的代码中还有其他问题。就像提到的评论一样,您不需要额外的行数。一旦你有了第一个while循环,你就会到达文件的末尾。后面的代码就没有意义了。

其次,您不需要两个for loops。只需对字符串的每个line使用基于范围的 for 循环,并在迭代时将其转换为整数并保存到 vector。

while (getline(in_file, line)) 
{
std::vector<int> dot_row; dot_row.reserve(str.size());
for (const std::string& eachChar: line) 
{
std::string CharString(1, eachChar);
dot_row.push_back(std::stoi(CharString));
// or other option mentioned above
}
dot_vector.push_back(dot_row);
}