【问题标题】:Print a 2D Array from file in c++在 C++ 中从文件中打印二维数组
【发布时间】:2014-04-08 03:50:33
【问题描述】:

我有一个 Map.txt 文件,并且在该文件中保存了一个 2D 数组,但是每当我尝试在我的主程序中打印我的 2D 数组时,我都会得到疯狂的数字。代码:

  cout << "Would you like to load an existing game? Enter Y or N: " << endl;
cin >> Choice;
if (Choice == 'Y' || Choice == 'y')
{
   fstream infile;
   infile.open("Map.txt");
   if (!infile)
       cout << "File open failure!" << endl;
   infile.close();
}
if (Choice == 'N' || Choice == 'n')
    InitMap(Map);

地图保存在文件中:

********************
********************
********************
********************
********************
********************
********************
**********S*********
*****************T**
********************

程序运行时的输出:

Would you like to load an existing game? Enter Y or N: 
y
88???????`Ė
?(?a????
??_?
?дa??g  @
 Z???@

        ?
 ?a??p`Ė??p]?
??_???`Ė?
??a??#E@??
??_??

【问题讨论】:

  • 请准确显示文件的样子,以及实际尝试打印的代码的相关部分。
  • 你已经展示了打开和关闭文件的代码。把从文件中读取二维数组的代码和你得到什么样的输出。
  • 我不知道如何从文件中读取二维数组。
  • 那么你怎么能指望输出不疯狂呢?
  • 别管二维数组,你知道如何从文件中读取一个字符吗?您是否尝试过在 C++ 教科书中查找“文件”?还是网上搜索?你试过什么吗?

标签: c++ arrays file


【解决方案1】:

我将冒险猜测您想将文件读入二维字符数组。 为简单起见,我还将假设您知道需要多少行和列。以下数字仅供参考。

#define NUM_ROWS 10
#define NUM_COLS 20    

// First initialize the memory
char** LoadedMap = new char*[NUM_ROWS];
for (int i = 0; i < NUM_ROW; i++)
   LoadedMap[i] = new char[NUM_COLS];

// Then read one line at a time
string buf;
for (int i = 0; i < NUM_ROW; i++) {
   getline(infile, buf);
   memcpy(LoadedMap[i], buf.c_str(), NUM_COL);
}

// Sometime later, you should free the memory


for (int i = 0; i < NUM_ROW; i++)
   delete LoadedMap[i];

delete LoadedMap;

【讨论】:

    【解决方案2】:

    此代码将在控制台中显示您的 Map.txt 文件。不要忘记提供打开文件的确切路径。

    #include <stdio.h>
    
    const int MAX_BUF = 100001;
    char buf[MAX_BUF];
    
    int main()
    {
        FILE *fp = fopen("Map.txt","r"); //give the full file path here.
        while( fgets(buf,MAX_BUF,fp) )
        {
            puts(buf);
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 2023-04-09
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2014-12-21
      相关资源
      最近更新 更多