Witam,
Próbuję wczytać z pliku mapę do tablicy dynamicznej. Dwa pierwsze wiersze pliku to informacja o liczbie wierszy i kolumn mapy rastrowej (np. lines 10, columns 11), w kolejnych wierszach jest mapa.
Niby wszystko działa, ale kolejność elementów jest w tablicy przesunięta. Kiedy tworzę tablicę ze stałą liczbą elementów (i usuwam z pliku to co nie jest mapą) wszystko działa. Prośba o pomoc. Coś pomijam?
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
int lines, columns;
//funkcja odczytujaca z pliku ile jest wierszy i kolumn
void get_file_info(std::string word, int number)
{
if (word == "lines")
{
lines = number;
std::cout << "number of lines: " << lines;
std::cout << std::endl;
}
else if (word == "columns")
{
columns = number;
std::cout << "number of columns: " << columns;
std::cout << std::endl;
}
}
//otwarcie pliku i odczyt danych
bool open_file(std::string file_name)
{
std::ifstream file;
file.open(file_name.c_str());
if (!file.good())
return false;
int p = 0;
while (p < 2)
{
std::string a;
int b;
file >> a >> b;
get_file_info(a, b);
p++;
}
file.close();
return true;
}
int main()
{
std::string adress = "d:\\mapa4.txt";
//std::cout << "podaj dane pliku: \n";
//std::cin >> nazwa;
if (!open_file(adress))
std::cout << "File cannot be open!" << std::endl;
std::ifstream file;
file.open(adress.c_str());
char **map;
map = new char*[lines];
for (int i = 0; i < lines; i++)
map[i] = new char[columns];
//wczytanie danych do tablicy
while (!file.eof())
{
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < columns; j++)
file >> map[i][j];
}
}
//drukowanie tablicy
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < columns; j++)
std::cout << map[i][j] << '\t';
std::cout << std::endl;
}
delete map;
file.close();
std::cout << "file closed. \n";
return 0;
}