从顺序文件填充二维数组

Populating 2d array from sequential file

本文关键字:二维数组 填充 顺序文件      更新时间:2023-10-16

我正试图从文本文件中为2d数组赋值,这就是我所拥有的:

string line = "";
string temp = "";
string removechr = "{} ";
string sepchar = ",";
ifstream myfile("pt.txt", ios::in);
if(myfile.is_open()){
    while( getline(myfile,line)){
        //--Remove characters
        size_t found = line.find_first_of(removechr);
        while(found != string::npos){
            line.erase(found);
        }
        //--Assign Values
        for(int y = 0; y < YCOL; ++y){
            for(int x = 0; x < XROW; ++x){
                size_t found = line.find_first_of(sepchar);
                while(found != string::npos){
                        temp.insert(line.begin(),found);
                        map[y][x]=stoi(temp);
                        temp = "";
                        line.erase(line.begin(),(line.begin() + found) - 1) ;
                }
            }
        }//End of for loop  
    }
}

首先,我要删除不必要的字符({}和空格),然后运行一个循环来设置数组中的值。现在,当它找到第一个逗号时,我想将值插入到临时字符串中,这样它就可以被分配给数组。在所有这些之后,我删除了刚刚分配的部分。

这就是我想做的,但我似乎不工作,我希望有更好的方法。

您的问题似乎并不是打开文件和处理潜在错误。所以,这集中在实际的循环上。虽然您没有完全指定文件的格式,但似乎您得到了包含curlies和用逗号分隔整数的内容。目前尚不清楚每一行是在自己的一行上,还是可以拆分为多行(如果是后者;我会阅读整个文件,进行下面的转换,然后分发结果)。我假设每一行都在自己的行上:

std::string line;
for (int row(0); row != rows; ++row) {
    if (!std::getline(myfile, line)) {
        std::cout << "failed to read all rows!n";
        return false;
    }
    // remove curlies; spaces don't matter
    line.erase(std::remove_if(line.begin(), line.end(),
                              [](char c){ return c == '{' || c == '}'; }));
    std::replace(line.begin(), line.end(), ',', ' ');
    std::istringstream in(line);
    for (int col(0); col != cols; ++col) {
        if (!(in >> map[row][col]) {
            std::cout << "failed to read all columns in row " << row << "n";
            return false;
        }
    }
}

代码首先删除行中的垃圾,然后用空格替换逗号,因为这些逗号是整数的纯分隔符,然后只读取单元格。