how read char array(with some space) from file in c++ - c++

I am trying to create a maze map in txt file
here is the .txt file
7 7
e%
%% %%
%% %%%
%%% %%%
% %
% %
x % %%
7 and 7 are the number of rows and columns respectively. The spaces are the contents of the array too/
how can I print the spaces in c++
I have tried to code for it but it doesn't work with space:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
int rows = 0, cols = 0;
map >> rows >> cols;
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
map >> arr[i][j];
}
}
map.close();
cout << "This is the grid from file: " << endl;
for (int i = 0; i < rows; i++)
{
cout << "\t";
for (int j = 0; j < cols; j++)
{
cout << arr[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
first time to ask question hope you guys can get the point thanks a lot for helping

map >> arr[i][j]; is a formatted input. It skips whitespaces. You have to use a different method, e.g. std::basic_istream<CharT,Traits>::get or std::basic_istream<CharT,Traits>::getline
Here is an example with get()
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
int rows = 0, cols = 0;
map >> rows >> cols;
// Skip linebreak after line: 7 7
map.ignore();
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// Read each char, also whitespaces and linebreaks
arr[i][j] = map.get();
}
// Skip linebreak
map.ignore();
}
map.close();
cout << "This is the grid from file: " << endl;
for (int i = 0; i < rows; i++)
{
cout << "\t";
for (int j = 0; j < cols; j++)
{
cout << arr[i][j];
}
cout << endl;
}
return 0;
}
I had to add two map.ignore(); because the line
map >> arr[i][j];
skipped all linebreaks but
arr[i][j] = map.get();
would read them so we have to manually skip them.

To better clarify my answer (as Yunnosch asked). My point wasn't to solve all problems, only to point at the problem of why the initial code does not work. True, I didn't clarify, I only posted some "new" code.
Original code posted by Cynthia doesn't work because operator>> reads all characters until the first space. My approach was to read the whole line and then break it to the same nested vector as in the initial code. Be aware that this also reads and stores "7 7" line as part of arr
Edit: I had to add a few semicolons for it to compile, and I removed 'reserve' since it can only confuse fresh programmers.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
vector<vector<char> > arr;
string line;
// no need for size at start, we can deduce it from line size
while(getline(map, line))
{
vector<char> temp;
for (auto c : line)
temp.push_back(c);
arr.push_back(temp);
}
map.close();
cout << "This is the grid from file: " << endl;
// you can always get number of rows and cols from vector size
// additionally, each line can be of different size
for (int i = 0; i < arr.size(); i++)
{
cout << "\t";
for (int j = 0; j < arr.at(i).size(); j++)
{
cout << arr.at(i).at(j);
}
cout << endl;
}
system("pause");
return 0;
}

Related

Importing text from a .txt file into a 2D array of strings

I've been trying to import text from a .txt file into a 2D array of string, but it doesn't seem to be working. Each row in the .txt file has three values/elements separated that I need to copy.
This is the code:
// i am only allowed to use these libraries.
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
const int rows = 38;
const int columns = 3;
string companies[rows][columns];
// Inputting file contents
ifstream file;
file.open("companies.txt");
while(!file.eof())
{
for(int i = 0; i < 38; i++)
{
for(int j = 0; j < 3; j++)
{
getline(file, companies[i][j], ',');
}
}
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < 38; i++)
{
for(int j = 0; j < 3; j++)
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}
This is the data that I want to import :
Symbol,Company Name,Stock Price
ATRL,Attock Refinery Ltd.,171.54
AVN,Avanceon Ltd. Consolidated,78.1
BAHL,Bank AL-Habib Ltd.,54.97
CHCC,Cherat Cement Company Ltd.,126.26
One of the problems with your code is that you are only looking for , as a delimiter and not handling line breaks between the rows at all. Normally, I would suggest reading each row into a std::istringstream and then use std::getline(',') to parse each stream, but you say that you are not allowed to use <sstream>, so you will just have to parse each row manually using std::string::find() and std::string::substr() instead.
Also, using while(!file.eof()) is just plain wrong. Not just because it is the wrong way to use eof(), but also because your for loops are handling all of the data, so there is really nothing for the while loop to do.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int max_rows = 38;
const int max_columns = 3;
string companies[max_rows][max_columns];
string line;
string::size_type start, end;
// Inputting file contents
ifstream file("companies.txt");
int rows = 0;
while (rows < max_rows && getline(file, line))
{
start = 0;
for(int j = 0; j < max_columns; ++j)
{
end = line.find(',', start);
companies[rows][j] = line.substr(start, end-start);
start = end + 1;
}
++rows;
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < max_columns; ++j)
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}
Online Demo

How to convert 2D array into Vector

For example: [ticket.txt]
(Number) (Amount)
09 10
13 15
25 21
This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int rowNumber = 0;
ifstream inFile, inFile2;
string line;
inFile.open("Ticket.txt"); //open File
inFile2.open("Ticket.txt");
if (inFile.fail()) // If file cannot open, the code will end
{
cout << "Fail to open the file" << endl;
return 1;
}
while (getline(inFile2, line)) // get whole lines and two valid numbers(numbers and amounts)
++rowNumber;
cout << "Number of lines in text file: " << rowNumber << "\n";
int myArray[rowNumber][2]; //declare 2d array
for(int i = 0; i < rowNumber; i++)
for(int j = 0; j < 2; j++)
inFile >> myArray[i][j];
}
My code is running well, but I want to convert a 2d array into vector. While reading file by arrays has a fixed size, so vector is a good solution to solve this problem.
Given your file structure you can read lines into a temporary vector and then insert it into a vector of vectors:
#include <iostream>
#include <fstream>
#include <vector>
int main(){
std::ifstream myfile("Tickets.txt");
std::vector<int> temprow(2);
std::vector<std::vector<int>> matrix{};
int rowcount = 0;
while (myfile >> temprow[0] >> temprow[1]){
matrix.push_back(temprow);
rowcount++;
}
for (int i = 0; i < rowcount; i++){
for (int j = 0; j < 2; j++){
std::cout << matrix[i][j] << ' ';
}
std::cout << std::endl;
}
}
This assumes your 2D array is N * 2.

How to open a file in Sudoku?

I am trying to write a program for Sudoku. The Sudoku runs well for my input file. But I want to make some changes that input the file in the compiler. It catches the error like no matching member function for call to 'open'. This is just part of my program because I think my problem is the I/O file. Any help is appreciated! Thanks you!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char filename;
ifstream myfile;
//int row,column;
int choice;
cout << "Enter the desired sudoku 4 for (4x4) or 9 for (9x9) : \n";
cin >> choice;
if(choice == 9) {
for(int row = 0; row < 9; row++) // iterating the loop to assign initial dummy values
{
for(int column = 0; column < 9; column++)
{
sudoku[row][column] = 0; // assigining zeros
}
}
cout << "Enter the filename:" << endl;
cin >> filename;
myfile.open(filename); // opening the file mentioned
cout << "The values in the file are :" << endl;
if (myfile.is_open())
{
while (!myfile.eof())
{
for(int row = 0; row < 9; row++) // iterating the loope to get the values form the file
{
for(int column = 0; column < 9; column++)
{
myfile >> sudoku[row][column]; // assigning the values to the grid
cout << sudoku[row][column] << endl; // printing the grid
}
}
}
}
myfile.close(); // closing the file
solvesudoku(0,0);//We start solving the sudoku.
}
else if(choice == 4) {
for(int row = 0; row < 4; row++) // iterating the loop to assign initial dummy values
{
for(int column = 0; column < 4; column++)
{
sudoku1[row][column] = 0; // assigining zeros
}
}
cout << "Enter the filename:" << endl;
cin >> filename;
myfile.open(filename); // opening the file mentioned
cout << "The values in the file are :" << endl;
if (myfile.is_open())
{
while (!myfile.eof())
{
for(int row = 0; row < 4; row++) // iterating the loope to get the values form the file
{
for(int column = 0; column < 4; column++)
{
myfile >> sudoku1[row][column]; // assigning the values to the grid
cout << sudoku1[row][column] << endl; // printing the grid
}
}
}
}
myfile.close(); // closing the file
solsudoku(0,0);//We start solving the sudoku.
}
else {
cout << "Invalid Choice..!!!";
}
return 0;
}
Your filename variable has type char. That is a single integral value that can store one "character".
The compiler is correct when it says that no fstream constructor takes a filename of type char.
You probably meant char[SOME_BUFFER_SIZE], or ideally std::string.
Note that if you use std::string and you move to a C++03 compiler, you'll have to append c_str() when you pass it to the fstream, for historical reasons.

Row transposition cypher using extra column

Hi guys I am trying to make a program that takes some user input and maps it to a 2d array and then encrypts it by mixing up the columns. For example if the user enters "my name is fred" the program creates an array that is 3x6 filling the last column with y's and the remain empty spaces with x's so it should be something like
mynamy
eisfry
edxxxx
instead I wind up with
mynam
eisfr
edxx
#include <iostream>
#include<cctype>
#include<algorithm>
using namespace std;
main(){
string input;
cout << "Enter information to be encrypted" << endl;
getline(cin,input);
input.erase(std::remove (input.begin(), input.end(), ' '), input.end());
int columns = 6;
int rows;
if (input.size() <= 5){
rows = 1;
}
else if (input.size()% 5 > 0){
rows = input.size()/5 + 1;
}
else
rows = input.size()/5;
char message[rows][columns];
int place = 0;
for(int i = 0; i < rows; i++){
for(int j = 0; j < (columns-1); j++){
if(place <= input.size()){
message[rows][columns] = input[place];
}
else {
message[rows][columns] = 'x';
}
place++;
message[rows][5] = 'y';
cout << message[rows][columns];
}
cout << endl;
}
}
this should do it..
#include <iostream>
#include <cctype>
#include <algorithm>
using namespace std;
int main()
{
string input;
cout << "Enter information to be encrypted" << endl;
getline(cin,input);
input.erase(std::remove (input.begin(), input.end(), ' '), input.end());
int columns = 6;
int rows;
if (input.size() <= 5){
rows = 1;
}
else if (input.size()% 5 > 0){
rows = input.size()/5 + 1;
}
else
rows = input.size()/5;
char message[rows][columns];
for(int i = 0; i < rows; i++){
for(int j = 0; j < (columns-1); j++){
if ((i*5 + j) < int(input.size())){
message[i][j] = input[i*5 + j];
}
else {
message[i][j] = 'x';
}
// place++;
if (i != rows-1) message[i][5] = 'y';
else message[i][5] = 'x';
// cout << "i: " << i << " | j: " << j << " | " << message[i][j] << endl;
}
cout << endl;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << message[i][j];
}
cout << " ";
}
cout << endl;
}
Your code isn't actually doing anything to transpose the matrix! It's writing the message into the matrix, but it's printing each entry out right after it's written, so it doesn't end up changing the order at all.
You'll need a separate set of loops to read data out of the matrix.

Reading Text File of Floats into a 2D Vector in C++

I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}