读取字符串文本输入以创建二维向量

reading string text input to create a 2D Vector

给定一个常规文本文件:

56789
28385
43285
22354
34255

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

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

在我的二维向量中输出每一列和每一行时,我想要完全相同的输出:

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

std::stoi 期望一个字符串作为参数,你提供的是一个 int.

您可以将 char 转换为字符串 并调用 std::stoi,如下所示

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

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

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

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

其次,你不需要两个for loops。只需对每个 line 字符串使用基于范围的 for 循环,并在遍历它时,转换为整数并保存到向量。

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);
}