每次从文件中读取一个字符(c++)并存储到2D数组中
Reading characters from a file one at a time (C++) and storing to a 2D array?
所以我在c++中阅读文本文件时遇到了一点麻烦。我要做的是从一个包含字母网格的文本文件中读取。下面是我的设置:
int main()
{
char grid[10][10];
ifstream input;
input.open("puzzle1_size10.txt");
//what goes here
input.close();
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
cout<< grid[i][j]<<" ";
cout<<endl;
}
}
文本文件如下:
10 10
f e h l o a k r a y
e s r r t s c d o y
a l u g d o e e g a
t c y y m h l j y a
u r a p s y n a r j
r e u d c a e p e r
e t s o c h t p h c
e g o p e h w l t w
h h c l s d o e c a
l n h c a m r l e e
前两个数字表示网格的大小。我试图读取每个字符(忽略初始数字)并将字符存储到称为网格的数组中。任何建议吗?
我在stackoverflow上发现了其他类似的问题,但没有一个与此背景相同,也没有一个给我一个明确的答案。我只是想一次从文件中读取一个字符,并将该字符存储到2D数组中,以便数组中的每个字母都可以轻松引用。有人能帮帮我吗?
我相信你在找这样的东西吧?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char grid[10][10];
ifstream input;
input.open("File.txt", ios::in);
int column = 0;
int row = 0;
input >> column >> row;
for (int column_counter = 0; column_counter < column; column_counter++){
for (int row_counter = 0; row_counter < row; row_counter++){
input >> grid[column_counter][row_counter];
}
}
input.close();
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
cout<< grid[i][j]<<" " << endl;
cout<<endl;
}
}
我首先取前两个数字,并将它们命名为列和行。然后在两个for循环中,我添加了计数器来计算网格的位置,直到它们达到文件开头指定的位置。
如果你有任何问题就问!我很快就会给它们添加评论。我现在正在一家咖啡馆里。
因为它被标记为c++
,我建议您使用std::vector
而不是普通数组,这样您就有了一种更灵活的方法
std::string line;
getline(file, line); // skip first line
std::vector<std::vector<char>> grid;
while(getline(file, line))
{
std::vector<char> insideV (line.begin(), line.end()); // read string into vector of char
grid.push_back(insideV);
}
......
std::cout << grid[0][0]; // f
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '