Question

I need this to save the map of a game I'm making, I use this code to save the array to a txt file:

void saveMap(string name){
    ofstream myFile;
    myFile.open(name.c_str());
    for (int y = 0; y < 100; ++y){
        for (int x = 0; x < 257; ++x){
            myFile << blocks[x][y].get() << ",";
        }
        myFile << '\n';
    }
    myFile.close();
}

so i would end up with something like:

0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,1,1,0,0,1,1,0,
0,1,1,0,0,1,1,0,
0,0,0,2,2,0,0,0,
0,0,2,2,2,2,0,0,
0,0,2,2,2,2,0,0,
0,0,2,0,0,2,0,0,

(except terrain-like and 257 x 100) then i want to load that into the blocks array. I need the values to be separated by commas because some of the block ids I will be saving are multi-digit.

I can't figure out how to achieve this in code, especially with the comma separation, I've done plenty of research and found nothing so i thought i would ask this lovely community.


Thanks for all the help i got it working with this function:

void loadMap(string name){
    std::ifstream file(name.c_str());
    std::string line;
    int i=0,j=0;
    while (std::getline(file, line)){
       std::istringstream ss(line);
       std::string data;
        while (std::getline(ss, data, ',')){
            blocks[i][j].set(atoi(data.c_str()),1,true);
            i++;
        }
        i=0;
        j++;
    }
}
Was it helpful?

Solution

You can tell getline to use a custom character for the next "line"

std::ifstream file("data.txt");
std::string line;
while (std::getline(file, line))
{
    std::istringstream ss(line);
    std::string data;
    while (std::getline(ss, data, ','))
    {
        // use data
    }
}

OTHER TIPS

I hope this code may help You to read a comma separated file.

ifstream infile( "test.txt" );

  while (infile)
  {
    string s;
    if (!getline( infile, s )) break;

    istringstream ss( s );
    vector <string> record;

    while (ss)
    {
      string s;
      if (!getline( ss, s, ',' )) break;
      record.push_back( s );
    }

    data.push_back( record );
  }
  if (!infile.eof())
  {
    cerr << "Fooey!\n";
  }

Read More here Source :: http://www.cplusplus.com/forum/general/17771/

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