'?' 而是文件中的普通文本

Чер*_*ень 1 c++ cout file ifstream multidimensional-array

我有此代码的文件:

start:
    var: a , b , c;
    a = 4;
    b = 2;
    c = a + b;
    wuw c;
    end;/
Run Code Online (Sandbox Code Playgroud)

我创建了一个类,其中包含我的代码所在的字符数组:

class file{               //class of program file
    private:
    ifstream File;        //file
    char text[X][Y];      //code from file
Run Code Online (Sandbox Code Playgroud)

我使用类的构造函数将文件中的信息加载到数组中:

   file(string path)
    {
         File.open(path); //open file

         for(int x = 0 ; x < X ; x++)
         {  
              for (int y = 0; y < Y ; y++) text[x][y] = File.get();     
         }
    }
Run Code Online (Sandbox Code Playgroud)

在类中,我具有从数组写入控制台文本的功能:

void write()
{                        
    for (int x = 0 ; x < X ; x++)
    {
         for (int y = 0 ; y < Y ; y++) cout << text[x][y];

    }
}
Run Code Online (Sandbox Code Playgroud)

但是在调用write()函数之后,我得到了以下文本:

start:
    var: a , b , c;
    a = 4;
    b = 2;

    c = a + b;
    wuw c;
    end;/

???????????? 
???????????????????????????????????????? 
???????????????????????????????????????? 
???????????????????????????????????????? 
???????????????????????????????????????? 
???????????????????????????????????????? 
Run Code Online (Sandbox Code Playgroud)

Jon*_*Mee 5

的大小text与文件的大小不对应。这不仅浪费,而且在这种情况下,这会导致您读取文件末尾。更好的设计是改为定义vector<string> text。使用有效值,ifstream File您可以text像这样在构造函数的主体中填充此代码:

for(string i; getline(File, i); text.push_back(i));
Run Code Online (Sandbox Code Playgroud)

从那里,您还需要适应write

copy(cbegin(text), cend(text), ostream_iterator<string>(cout, "\n"));
Run Code Online (Sandbox Code Playgroud)

您还需要进行安全检查,以确保索引传入no_zeroret_char有效,但是其余代码应按原样工作。

Live Example

  • 基本上; 编写C ++而不是(不好的)C。同意。 (3认同)