Question

I am trying to assign values to a 2d array from a text files, this is what i have:

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

First i am removing the unnecessary characters ({ } and space), then after that i am running a loop to set the values in the array. So now when it find the first comma , i want to insert the value to the temp string, so it can be assigned to the array. After all of that i removed the part just assigned.

That's what i want to do but i doesn't seem to work, i hope there is a better way to do this.

Was it helpful?

Solution

It seems, your question isn't really about opening the file and dealing with potential errors there. So, this concentrates on the actual loop. You didn't quite specify the format of your file, though but it seems you get something which contains curlies and separate integers by commas. It is unclear whether each row is on its own line or if it may be split across multiple lines (if the latter; I'd read the entire file, do the transformations below and distribute the result then). I'm assuming each row is on its own line:

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

The code first removes the junk from the lines, then replaces commas by spaces as these are neat separators for integers anyway, and then just reads the cells.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top