(C++) I've created a function to open the text file and assign the contents to an array. The first 2 elements in the array are the size of the grid. However, if either or both of the first 2 numbers are double digits, it doesnt read them in as double digits. Is there any way of doing this?
int openMap()
{
std::string fileName;
std::cout << "Please enter the file name with extension that you want to open: ";
std::cin >> fileName;
system("CLS");
std::ifstream file(fileName); //OPENS MAP FILE
int tmp;
int i = 0;
if (!file.is_open()) //CHECKS IF THE MAP FILE HAS OPENED CORRECTLY
{
std::cout << "Error Occured!\nCould not open file.";
return 0;
}
while (!file.eof()) //READS THE MAP FILE AND PASSES THE INFORMATION INTO AN ARRAY
{
file >> tmp;
checkNumber(tmp);
if (valid == true) //IF THE CHARACTER IS NOT A NUMBER THEN IT WONT BE PASSED INTO THE ARRAY
{
tmpArray[i] = tmp;
i++;
valid = false;
}
row = tmpArray[1]; //ASSIGNS THE FIRST 2 NUMBERS OF THE MAP FILE TO ROW AND COL VARIABLES
col = tmpArray[0];
}
return row, col;
}
I would assume I have to rewrite
file >> tmp
in some sort of different way, but not sure how.
Is there a way to scan through the text file until it hits a whitespace?
The text file contents looks like this
6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0
(the 6 or 4 or both can be double digits instead)
Edit:
for (int j = 0; j < row; j++)
{
for (int k = 0; k < col; k++)
{
_map[j][k] = tmpArray[l];
std::cout << _map[j][k] << " ";
l++;
}
}
There's quite a number of bugs in the code, you should probably use a debugger to step through and identify which parts of your program don't behave as expected.
while(!file.eof())
file >> tmp;
checkNumber(tmp);
if (valid == true) //IF THE CHARACTER IS NOT A NUMBER THEN IT WONT BE PASSED INTO THE ARRAY
{
tmpArray[i] = tmp;
i++;
valid = false;
}
row = tmpArray[1]; //ASSIGNS THE FIRST 2 NUMBERS OF THE MAP FILE TO ROW AND COL VARIABLES
col = tmpArray[0];
You set row=tmpArray[1] and col = tmpArray[0] every iteration of the loop which is not only unnecessary but also incorrect, especially since row=tmpArray[1] is being executed at i=0 when nothing has been placed in tmpArray[1] yet.
EDIT: This is a lot smaller, less error prone due to less variables and type conversions, and easier to read:
int row,col;
//Add error checking here
cin >> col;
cin >> row;
cout << "Cols: " << col << " Rows: " << row << endl;
vector<vector<int> >_map(row, vector<int>(col,0));
for(int j=0; j < row; j++)
{
for(int k=0; k < col; k++)
{
int tmp;
cin >> tmp;
//Add error checking for tmp
_map[j][k] = tmp;
cout << _map[j][k] << endl;
}
}
There are some problems with your code. First the return type of your function is int but you are returning multiple values. Here is a complete running code which should solve your problem.
#include <iostream>
#include <fstream>
#include <vector>
std::vector< std::vector<int> > openMap() {
std::string fileName;
std::cout << "Please enter the file name with extension that you want to open: ";
std::cin >> fileName;
std::fstream myfile(fileName, std::ios_base::in);
int row, col;
myfile >> row;
myfile >> col;
int a;
std::vector< std::vector<int> > retval;
for (int i = 0; i < row; i++) {
std::vector<int> v1;
for (int j = 0; j < col; j++) {
myfile >> a;
v1.push_back(a);
}
retval.push_back(v1);
}
return retval;
}
int main(int argc, char * argv[])
{
std::vector< std::vector<int> > _map = openMap();
for(int i = 0; i < _map.size(); i++) {
for (int j = 0; j < _map[i].size(); j++) {
std::cout << _map[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
I guess that not so many people will be interested. But please see below a possible solution to your problem.
The code uses modern C++ algorithms.
It is very simple and straightforward.
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
// Ask user, to give a filename
std::cout << "Please enter the file name with extension that you want to open: ";
// Get the filename from the user
if (std::string fileName; std::cin >> fileName) {
// Open the file and check, if it is open
if (std::ifstream sourceFile(fileName); sourceFile) {
// Read the number of rows and columns of the matrix
if (size_t numberOfColumns, numberOfRows; sourceFile >> numberOfColumns >> numberOfRows) {
// Create a matrix with the given number of rows and columns
std::vector<std::vector<int>> result(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Read data from the input stream and put it into the matrix
for (size_t i = 0; i < numberOfRows; ++i) {
std::copy_n(std::istream_iterator<int>(sourceFile), numberOfColumns, result[i].begin());
}
// Print result. Go through all lines and then copy line elements to std::cout
std::for_each(result.begin(), result.end(), [](std::vector<int>& c) {
std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; });
}
}
else {
std::cerr << "\n*** Error: Could not open source File\n\n";
}
}
return 0;
}
Related
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;
}
I have a .dat file containing full of integers 100 by 100, and I am trying to transfer x rows and x columns into a new vector, I've managed to ge the first row with the desired columns but stuck in trying to get to the next line and until to the x rows, please give help. This is my code so far
also some help on the display part, I'm not sure how to display a vector with more than one rows and columns. Tried data.at(i).at(j) double for loop but unsuccessful
//variable
int row, col;
string fname;
ifstream file;
vector<int> data;
//input
cout << "Enter the number of rows in the map: "; cin >> row;
cout << "Enter the number of columns in the map: "; cin >> col;
cout << "Enter the file name to write: "; cin >> fname;
//open file
file.open(fname, ios::in); // map-input-100-100.dat
int temp;
for (int i = 0; i < col; ++i)
{
file >> temp;
data.push_back(temp);
}
// display first row of data
for (int i = 0; i < data.size(); ++i) cout << data.at(i) << ' ';
cout << endl;
The code could be like this:
vector<vector<int>> data; // instead of your definition of data:access data[r][c]
for (int j = 0; j < row; ++j)
{
vector<int> x(column);
for (int i = 0; i < col; ++i)
{
file >> temp;
x[i] = temp;
}
data.push_back(x);
}
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.
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.
Let's say we have a .txt file with data like this:
6
Paris New_York 1
London Berlin 1
Moskow Kiev 1
Paris London 1
New_York Moscow 1
Where 6 is number of Citys and than it means Paris and New_York are connected with value 1, it will always be 1.
Now i would like to turn this into 2D dynamic array. I did it with numbers like this, but i don't know how should i do this with strings.
For numbers:
ifstream myfile("info.txt");
if (myfile.is_open()) {
getline(myfile, line);
istringstream(line) >> Number;
}
int **matrix= new int*[Number];
for (int i = 0; i < Number; i++) {
matrix[i] = new int[Number];
}
while (getline(myfile, line)) {
cout << line << '\n';
std::stringstream linestream(line);
int row;
int column;
int value;
if (linestream >> row >> column >> value)
{
a[row-1][column-1] = value;
a[column-1][row-1] = value;// mirror
}
So how can i do this for strings?
Thank you for your helpful answers
You need an unordered_map<string, int>, beside the matrix, to map string to indexes. Here is my solution:
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <unordered_map>
using namespace std;
int main() {
string line;
int Number;
ifstream myfile("info.txt");
if (myfile.is_open()) {
getline(myfile, line);
istringstream(line) >> Number;
}
int **matrix= new int*[Number];
for (int i = 0; i < Number; i++) {
matrix[i] = new int[Number](); // note () at the end for initialization to 0
}
unordered_map<string, int> citiesMap; // to map cities (string) to indexes (int)
int cityIndex = 0;
while (getline(myfile, line)){
std::stringstream linestream(line);
string row;
string column;
int value;
if (linestream >> row >> column >> value) {
if(citiesMap.find(row) == citiesMap.cend())
citiesMap[row] = cityIndex++; // add city to the map if it doesn't exist
if(citiesMap.find(column) == citiesMap.cend())
citiesMap[column] = cityIndex++; // add city to the map if it doesn't exist
matrix[citiesMap[row]][citiesMap[column]] = value;
matrix[citiesMap[column]][citiesMap[row]] = value;// mirror
}
}
for(auto x: citiesMap) {
cout << x.first << ": " << x.second << endl;
}
cout << endl;
for(int i = 0; i < Number; i++) {
for(int j = 0; j < Number; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// matrix should be freed here
}
You may optionally keep unique cities in a vector (or array) to access cities from their indexes. Don't forget to free the memory. Also, you may use std::array for the matrix and don't bother with memory issues.