0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++でファイルから一文字づつ読み込む方法

Posted at

C++でファイルから一文字づつ読み込む方法

内容

以下のようなテキストデータ(map_data.txt)を読み込んでそのまま整数データとして格納する方法をメモ。

11111
10001
10001
11111

1:障害物
0:通行可能

想定としては、A-starのような経路探索用に地図をグリッドデータとして保存する場合でしょうか。
意外と目的にストレートに合うものがなかったので、初心者ですが何かの役に立てば。

システム

OS  :Windows10からVirtualBoxを使ってUbuntu 16.04上で
言語 :C++

コード

qiita.rb
# include<iostream>
# include<Windows.h>
# include<stdlib.h>
# include<fstream>
using namespace std;

int main(){
	int i,j;
	char ch;
	int map_x = 5;
	int map_y = 4;
	int road_data[5][4] = {};

	i = 0;
	j = 0;

	ifstream fp("map_data.txt");

	if(fp.fail()){
		cout << "Can't Open the file!\n";
		exit;
	}
	
	while(fp.get(ch)){
		if(ch != '\n'){
			road_data[j][i] = atoi(&ch);
			i = i + 1;
		}else{
			i = 0;
			j = j + 1;
		}
	}

	for (i = 0; i<map_y; i++){
		for (j = 0; j<map_x; j++){
			cout << road_data[i][j];
		}
		cout << "\n";
	}
	
	cout << "1:Obstacle\n";
	cout << "0:Road\n";
	
	return 0;

}

流れは以下の通り。
①ファイルを開く
②ファイルから一文字読み込んで(fp.get(ch))
③改行文字(\n)でないか判定して
④改行文字でないなら、読み込んだ文字(文字で読み込まれます)を整数に変換し(atoi(ch))データ格納用の変数(road_data)の行方向に格納※atoiを使用する場合は#includeが必要
⑤改行文字なら、格納先の変数の列を移動して(i = i + 1)
⑥続けて行方向に格納していく
⑦ ②~⑥をファイル終端まで継続
⑧最後に、格納したデータを確認のために表示

また、すぐわからなくなるんですが、配列の行列はarray[i][j]を例にとると、
  →j(行)

i
(列)

となっています。参考までに。

地図データのサイズが固定されていたり手抜きなところもありますが、以上よろしくお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?