【发布时间】:2017-12-04 02:41:11
【问题描述】:
目前正在从事一个学校项目,该项目涉及一个代表房间自上而下视图的 2D 字符数组,其中“W”= 墙壁,“F”= 家具,“”= 可用空间。该数组旨在从文件中读取(文件内容如下)。
文件:
2
W W W W W W W W W W
W F F F W
W F F F F F W
W F F F F F W
W F F F F F W
W F F F F F W
W F F F F F W
W F F F F F W
W F F F W
W F F F W
W F F F W
W F F F F W
W F F F F W
W F F W
W W W W W W W W W W
W W W W W W W W W W
W F F F F F F W
W F F F F F F W
W F F F F F F W
W F F F F F W
W F F F F F W
W F F F F F W
W F W
W F F W
W F F F F W
W F F F F F W
W F F F F F W
W F F F F F F W
W F F F F F F W
W W W F W W W W W W
“2”暂时无关紧要 - 它代表房间配置的数量。我知道我将不得不在项目后期使用该号码进行循环。
不过,在我开始项目之前,我想打印出我的输入,以确保我正确地读取了文件。无论我尝试什么,我似乎都无法获得正确的配置。我在我的代码中的多个点尝试了 >> skipws 和 file.get() ,使用它们给了我不同的输出,但没有一个与原始文件匹配。
我当前的代码:
int main()
{
//Variables
int i;
int j;
char room_array[room_height][room_width];
char piece_of_room;
int num_of_room_configurations;
//Create File, Open File, and Check File
ifstream room_file;
room_file.open("C:\\(path)\\rooms.txt");
if (room_file.fail())
{
cout << "Could not open file." << endl;
system("pause");
return 0;
}
//Loop Control / Use File; The Number of Room Configs (will need to put this in a loop later)
room_file >> num_of_room_configurations;
cout << "Number of different room layouts: " << num_of_room_configurations << endl << endl;
//Create Room Array / Use File
for (i = 0; i < room_height; i++) //moves through rows
{
cout << endl;
for (j = 0; j < room_width; j++) //moves through columns
{
room_file >> piece_of_room; //reading in values from file
room_array[i][j] = piece_of_room;
}
}
//Echo Original Room Layout
cout << endl << "ORIGINAL ARRAY:" << endl;
for (i = 0; i < room_height; i++) //moves through rows
{
cout << endl;
for (j = 0; j < room_width; j++) //moves through columns
{
cout << room_array[i][j]; //formatting
}
}
cout << endl << endl;
system("pause");
return 0;
我已尝试包含空格以使代码不那么复杂,因此使用此特定代码我将其作为输出:
对于这么长的问题,我深表歉意,但我想确保我没有遗漏任何可以帮助别人帮助我的东西。无论如何,我对 C++ 都没有很好的理解,所以我很可能遗漏了一些非常基本的东西。任何帮助都将非常感激,在此先感谢您。
另外,这是我的第一篇文章 - 如果我做错了什么,请告诉我,如果可能,我会编辑。
【问题讨论】:
标签: c++ arrays loops formatting output