读取字符串文本输入以创建 2D 矢量
reading string text input to create a 2D Vector
给定一个常规文本文件:
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);
}
相关文章:
- 读取字符串文本输入以创建 2D 矢量
- 如何使用 DXGI 格式DXGI_FORMAT_R1_UNORM创建 2D 纹理?
- 从 2 个 1D 矢量创建 2D 矢量
- 不明白使用双指针 (**) 创建 2d 动态数组
- 创建 2D 数组0xCCCCCCCC访问冲突写入位置
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 创建 2D 数组类:如何访问 2D 数组类(如 array[x][y))中的元素
- C++ - 创建 2D 复制构造函数
- 如何在其中创建2D字符串向量并插入数据
- 使用来自C 参数的大小创建2D数组
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 如何使用矢量创建 2D 数组
- 动态创建 2D 数组时使用的大小
- 从文本文件创建 2D 字符串矢量
- 从 1D 数组创建 2D 数组
- C++以内存安全的方式使用给定向量的大小创建2D阵列
- C++ 如何动态创建 2D 矢量
- 创建2D数组时出现异常:在C++中重新抛出之前进行清理
- 基于命令行输入创建 2D 数组