替换2D数组中的特定值

时间:2014-10-01 15:52:31

标签: c++ arrays file file-io multidimensional-array

我有一个包含以下值的文件:

0 0 0
0 0 0
0 0 0

通过以下代码加载2D数组:

string Seats[10][10]; // creates array to hold strings 

short loop1 = 0; //short for loop for input
short loop2 = 0; //short for loop for input

string line; //this will contain the data read from the file
ifstream BookingFile("test.txt"); //opening the file.

if (BookingFile.is_open()) //if the file is open
{
    cout << "These are the available seats: \n" << endl;
    while (!BookingFile.eof()) //while the end of file is NOT reached
    {
        getline(BookingFile, line); //get one line from the file
        Seats[loop1][loop2] = line;
        cout << Seats[loop1][loop2] << endl; //and output it
        loop1++;
        loop2++;
    }
}

我现在想做的只是找到一种方法来改变数组中的特定值。我用过

array[rows][cols]

以前编辑这些值,但这不适用于外部文件,我似乎无法获取

seats << [rows][cols]

工作,那么最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

将文件读入数组,根据需要更改单元格,然后将其写回。

写入文件将涉及像以前一样打开它,但是作为ofstream(输出文件STREAM),并以类似于你如何读取它们的方式将它们写出来(一旦你得到它)正确阅读它们。)