【问题标题】:Parsing ASCII Text file into 2d Vector of Char's将 ASCII 文本文件解析为 Char 的二维向量
【发布时间】:2018-11-07 19:18:45
【问题描述】:

我需要帮助,我正在尝试读取一个看起来像这样的文件:

.........
.........
.........
.........
....X....
.........
.........
.........
.........

我需要将其解析为 2d 字符向量,以便稍后对其进行修改。

到目前为止,我想出的是

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
//look up line by line parsing
using namespace std;
int main(int argc, char* argv[]) {
    vector<vector<char>> data;
    ifstream myReadFile;
    myReadFile.open("input1.txt");

    for (int i = 0; i < data.size(); i++) {
        int c = 0;
        char currentchar;

        while (!myReadFile.eof()) {
            data[i][c] = currentchar;
            c++;
            currentchar = myReadFile.get();
        }
    }

    //for ()


    myReadFile.close();


    return 0;
}

【问题讨论】:

  • Re: i &lt; data.size() -- data.size() 为 0,因此不会运行循环体。你知道网格的尺寸吗?
  • 这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是使用默认构造函数创建它们并立即更改它们。即把ifstream myReadFile; myReadFile.open("input1.txt');改成ifstream myReadFile("input1.txt");
  • @PeteBecker 谢谢,我是 C++ 新手,请记住这一点

标签: c++ parsing vector


【解决方案1】:

在通过data[i][c] = currentchar; 为其赋值之前,您需要在向量中保留空间。但是在阅读内容之前可能很难保留空间。

更简单的方法是使用向量的动态增长功能(即push_back),并使用std::string 作为行内容,因为您可以轻松阅读完整的行。您仍然可以通过data[i][c] = currentchar; 访问/更改内容。请参阅以下代码来说明这一点:

#include <sstream>
#include <iostream>
#include <vector>

int main() {

    const char* fileContent = R"foo(.........
.........
.........
.........
....X....
.........
.........
.........
.........)foo";

    std::vector<std::string> lines;
    stringstream ss(fileContent);
    string line;
    while (getline(ss,line)) {
        lines.push_back(line);
    }

    lines[2][5] = 'Y';

    for (auto line : lines) {
        for (auto c : line) {
            cout << c << " ";
        }
        cout << endl;
    }
}

输出:

. . . . . . . . . 
. . . . . . . . . 
. . . . . Y . . . 
. . . . . . . . . 
. . . . X . . . . 
. . . . . . . . . 
. . . . . . . . . 
. . . . . . . . . 
. . . . . . . . . 

【讨论】:

  • 谢谢!我能够修改您的解决方案以处理用户输入的文本文件。
【解决方案2】:

您可以使用std::getlinestd::string 让生活更轻松:

std::string row_text;
std::vector<std::string> grid;
while (std::getline(myReadFile, row_text))
{
  grid.push_back(row_text);
}

std::string 可以使用数组表示法访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多