【问题标题】:load txt file into a 2 dim array values seperated with cammas C++将 txt 文件加载到用逗号 C++ 分隔的 2 个暗淡数组值中
【发布时间】:2014-03-30 21:39:44
【问题描述】:

我需要这个来保存我正在制作的游戏的地图, 我使用此代码将数组保存到 txt 文件:

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

所以我最终会得到类似的东西:

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,

(地形类和 257 x 100 除外) 然后我想将它加载到块数组中。 我需要用逗号分隔这些值,因为我要保存的一些块 ID 是多位的。

我不知道如何在代码中实现这一点,尤其是在逗号分隔的情况下,我做了很多研究但一无所获,所以我想我会问这个可爱的社区。​​p>


感谢所有帮助我使用此功能:

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

【问题讨论】:

标签: c++ arrays text-files ifstream


【解决方案1】:

您可以告诉getline 为下一个“行”使用自定义字符

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

【讨论】:

  • 他还需要将字符串转换为整数。为此,他可以使用std::stoi()
  • @0x499602D2 是的,我把数据的实际使用留给读者作为练习:)
  • @ std::getline(line, data, ','),我得到一个错误:没有匹配函数调用'getline(std::string&, std::string&, char)'
  • 没关系,我发现它应该是 'ss' 插入的 'line' 有意义
  • @MurderFish612 哎呀抱歉
【解决方案2】:

我希望这段代码可以帮助您阅读逗号分隔的文件。

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

在这里阅读更多 来源::http://www.cplusplus.com/forum/general/17771/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多