[英]Storing input file into a 2d array C++
我有一个输入文件,我想通过使用cin
来使用。 我的输入文件包含9x9数字的列表,例如:
1 2 3 4 5 6 7 8 9
2 2 3 4 5 6 7 8 9
3 2 3 4 5 6 7 8 9
4 2 3 4 5 6 7 8 9
5 ...
6 ...
7 ...
8 ...
9 ...
我想将这些值存储到2d数组中,所以它们看起来像:
int board[9][9] = {{1, 2, 3, 4, 5, 6, 7, 8, 9},
{2, 2, 3, 4, 5, 6, 7, 8, 9},
{3, 2, 3, 4, 5, 6, 7, 8, 9},
{4, 2, 3, 4, 5, 6, 7, 8, 9},
{5, 2, 3, 4, 5, 6, 7, 8, 9},
{6, 2, 3, 4, 5, 6, 7, 8, 9},
{7, 2, 3, 4, 5, 6, 7, 8, 9},
{8, 2, 3, 4, 5, 6, 7, 8, 9},
{9, 2, 3, 4, 5, 6, 7, 8, 9}};
我试着做:
int board[9][9];
for (int i=0;i<9;i++) {
for (int j=0;j<9;j++) {
std::cin >> board[i][j];
}
}
但是,我认为它没有用。 我将在运行代码时将它们用作输入。
这在使用C ++ 11的GCC 4.9.0中对我有效:
样例代码:
#include <iostream>
int main() {
int board[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
std::cin >> board[i][j];
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
std::cout << board[i][j];
}
std::cout << std::endl;
}
return 0;
}
您应该从STL更改std::vector
或其他容器的C array
,它提供了很多好处(自动内存管理,数组绑定检查等)。 如果您可以使用C ++ 11,那么新的循环范围也将是一个很大的改进(在语法和性能方面,它避免了因错误而导致的错误,错误的边界等)。
这是C ++ 11版本:
#include <iostream>
#include <vector>
int main() {
typedef std::vector<int> row_t;
typedef std::vector<row_t> board_t;
board_t board(9, row_t(9));
for (auto& row : board) {
for (auto& cell : row) {
std::cin >> cell;
}
}
for (const auto& row : board) {
for (auto cell : row) {
std::cout << cell;
}
std::cout << std::endl;
}
return 0;
}
内部循环是错误的,在那里您将j++
作为循环条件。 就像在第一次迭代中j
将为零(在C ++中,它与false
),循环根本不会迭代。 此外,内部循环缺少分号,因此甚至不应该编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.