我有这段代码的文件:
start:
var: a , b , c;
a = 4;
b = 2;
c = a + b;
wuw c;
end;/
我创建了一个包含我的代码所在的字符数组的类:
class file{ //class of program file
private:
ifstream File; //file
char text[X][Y]; //code from file
来自文件的信息我使用类的构造函数加载到数组:
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();
}
}
在类I中,我有从数组写入控制台文本的函数:
void write()
{
for (int x = 0 ; x < X ; x++)
{
for (int y = 0 ; y < Y ; y++) cout << text[x][y];
}
}
但是在调用write()函数之后我有了这个文本:
start:
var: a , b , c;
a = 4;
b = 2;
c = a + b;
wuw c;
end;/
������������
����������������������������������������
����������������������������������������
����������������������������������������
����������������������������������������
����������������������������������������
text
的大小与文件的大小不对应。这不仅浪费,而且在这种情况下,它会导致您读取文件的末尾。更好的设计是改为定义vector<string> text
。使用有效的ifstream File
,您可以在构造函数的主体中填充此text
,如下所示:
for(string i; getline(File, i); text.push_back(i));
从那里,你还需要调整write
:
copy(cbegin(text), cend(text), ostream_iterator<string>(cout, "\n"));
您还需要进行安全检查,以确保传入no_zero
和ret_char
的索引是有效的,但其余代码应该按原样运行。