Read 2d array from txt file in c++ [duplicate] - c++

This question already has answers here:
Characters duplicate in a multidimensional array
(3 answers)
Closed 1 year ago.
This is my code
#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout << "Reading Start" << endl;
ifstream rfile("test.txt");
rfile.getline(arr1[10], 10);
int i, j;
for (i = 0; i < 6; i++)
{
for (j = 0; i < 6; j++)
{
cout << arr1[i][j];
}
}
cout << "\nRead Done" << endl << endl;
rfile.close();
}
This is my test.txt file
0 4 7 0 0 0
4 0 0 5 3 0
7 0 0 0 6 0
0 5 3 0 0 2
0 3 4 0 0 2
0 0 0 2 2 0
I want to read this matrix but when using the above code then it shows core dumped output, can anyone give me a better solution to do this thing?

can anyone give me a better solution to do this thing?
A better alternative would be to use a 2D vector as shown below. The advantage of using a vector over an array is that you don't need to specify(know) the rows and columns beforehand. That is, the text input file can have as many rows and columns and there is no need to ask the user(or preallocate) how many rows and columns does the file have. std::vector will take care of it as shown below.
The below program uses a 2D std::vector for storing information(like integers values in this case) in 2D manner. After reading all the values from the file you can process the vector according to your needs. The program shown reads data(int values) from input.txt and store those in a 2D vector. Also, this program works even if there are uneven number of columns. You can use the below program as a reference(starting point).
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
int word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<int>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<int> tempVec;
std::istringstream ss(line);
//read word by word(or int by int)
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//now you can do the whatever processing you want on the vector
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<int> &newvec: vec)
{
for(const int &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
The output of the above program can be seen here. The input file through which int values are read is also given at the above mentioned link.
Advantages of using vector
You don't need to ask the user for the number of rows and columns in the input file. That is you don't have to fix(hardcode) the size of your array.
The above program works even if there are uneven entries in any particular row.
std::vector takes care of memory management for you. So you don't have to use new and delete by yourself which needs more attention/care.(in case you're thinking of creating array on heap)

Because there are so many possible solutions, let us just show some of them.
The basic difference is:
If we know the dimensions of the array at compile time, so, if there are compile time constants, then we can still use a C-Style array, or better, a std::array.
If we do not know the dimensions of the source data array, then we need a dynamic container that can grow, for example a std::vector.
In all cases, we can use the index operator [] with a standard for loop or a range based for loop with references. There is no difference.
Examples:
C-Style array with standard for loops and index based access
#include <iostream>
#include <fstream>
constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;
int main() {
// Open the sourcefile
std::ifstream sourceFileStream{ "test.txt" };
// And check, if it could be opened
if (sourceFileStream) {
// Define 2D array to hold all data and initialize it with all 0
char array2D[NumberOfRows][NumberOfColumns]{};
// Read the rows and columns from the source file
for (int row = 0; row < NumberOfRows; ++row)
for (int col = 0; col < NumberOfColumns; ++col)
sourceFileStream >> array2D[row][col];
// Debug output
for (int row = 0; row < NumberOfRows; ++row) {
for (int col = 0; col < NumberOfColumns; ++col) std::cout << array2D[row][col] << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError: Could not open source file\n\n";
}
C-Style array with range based for loop and reference access
#include <iostream>
#include <fstream>
constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;
int main() {
// Open the sourcefile
std::ifstream sourceFileStream{ "test.txt" };
// And check, if it could be opened
if (sourceFileStream) {
// Define 2D array to hold all data and initialize it with all 0
char array2D[NumberOfRows][NumberOfColumns]{};
// Read the rows and columns from the source file
for (auto& row : array2D)
for (auto& col : row)
sourceFileStream >> col;
// Debug output
for (const auto& row : array2D) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError: Could not open source file\n\n";
}
C++ std::array with range based for loop
#include <iostream>
#include <fstream>
#include <array>
constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;
int main() {
// Open the sourcefile
std::ifstream sourceFileStream{ "test.txt" };
// And check, if it could be opened
if (sourceFileStream) {
// Define 2D array toholdall data and initialize it with all 0
std::array<std::array<char, NumberOfColumns>, NumberOfRows> array2D{};
// Read the rows and columns from the source file
for (auto& row : array2D)
for (auto& col : row)
sourceFileStream >> col;
// Debug output
for (const auto& row : array2D) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError: Could not open source file\n\n";
}
Dynamic solution, with a std::vector
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
int main() {
// Open the sourcefile
std::ifstream sourceFileStream{ "test.txt" };
// And check, if it could be opened
if (sourceFileStream) {
// Define 2D array to hold all data and initialize it with all 0
std::vector<std::vector<char>> array2D{};
// Read the rows and columns from the source file
std::string line{};
while (std::getline(sourceFileStream, line)) {
// Add a new row to our matrix
array2D.push_back(std::vector<char>{});
// Read all column data
char c{};
for (std::istringstream iss(line); iss >> c; array2D.back().push_back(c))
;
}
// Debug output
for (const auto& row : array2D) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError: Could not open source file\n\n";
}
More modern and compact C++ solution
#include <vector>
#include <string>
#include <iterator>
int main() {
// Open the sourcefile and check, if it could be opened
if (std::ifstream sourceFileStream{ "test.txt"}; sourceFileStream) {
// Define 2D array to hold all data and initialize it with all 0
std::vector<std::vector<char>> array2D{};
// Read the rows and columns from the source file
for (std::string line{}; std::getline(sourceFileStream, line);) {
std::istringstream iss(line);
array2D.push_back({ std::istream_iterator<char>(iss), {} });
}
// Debug output
for (const auto& row : array2D) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError: Could not open source file\n\n";
}
And now, we imagine that we do not have any vector or even a string.
For that, we build a small class "DynamicArray" with some functions and an iterator. This can easily be extended.
And the result will be that in main, only one small statement, sourceFileStream >> dada; will read all the data into a 2d array.
Please note. We are only using stream functions for stream io, nothing more.
Cool . . .
#include <iostream>
#include <sstream>
#include <fstream>
// The Dynamic Array has an initial capacity.
// If more elements will be added, there will be a reallocation with doublecapacity
constexpr unsigned int InitialCapacity{ 4 };
// Definition of simple dynamic array class
template <typename T>
class DynamicArray {
protected:
// Internal data ------------------------------------------------------------------------------
T* data{}; // Dynamic Storage for Data
unsigned int numberOfElements{}; // Number oe elements currently in the container
unsigned int capacity{ InitialCapacity }; // Current maximum capacity of the container
public:
// Construction and Destruction ---------------------------------------------------------------
DynamicArray() { data = new T[capacity]; } // Default constructor. Allocate new memory
DynamicArray(const DynamicArray& other) { // Copy constructor. Make a deep copy
capacity = numberOfElements = other.numberOfElements;
data = new T[capacity]; // Get memory, same size as other container
for (size_t k = 0; k < other.numberOfElements; ++k)
data[k] = other.data[k]; // Copy data
}
~DynamicArray() { delete[] data; } // Destructor: Release previously allocated memory
bool empty() { return numberOfElements == 0; }
void clear() { numberOfElements = 0; }; // Clear will not delete anything. Just set element count to 0
void push_back(const T& d) { // Add a new element at the end
if (numberOfElements >= capacity) { // Check, if capacity of this dynamic array is big enough
capacity *= 2; // Obviously not, we will double the capacity
T* temp = new T[capacity]; // Allocate new and more memory
for (unsigned int k = 0; k < numberOfElements; ++k)
temp[k] = data[k]; // Copy data from old memory to new memory
delete[] data; // Release old memory
data = temp; // And assign newly allocated memory to old pointer
}
data[numberOfElements++] = d; // And finally, stor the given fata at the end of the container
}
// Add iterator properties to class ---------------------------------------------------------------
// Local class for iterator
class iterator{
T* iter{}; // This will be the iterator
public: // Define alias names necessary for the iterator functionality
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
explicit iterator(T* i) : iter(i) {}; // Default constructor for the iterator
T operator *() const { return *iter; } // Dereferencing
iterator& operator ++() { ++iter; return *this; } // Pre-Increment
bool operator != (const iterator& other) { return iter != other.iter; } // Comparison
};
// Begin and end function to initiliaze an iterator
iterator begin() const { return iterator(data); }
iterator end() const { return iterator (data + numberOfElements); }
// Operators for class------------------------ ---------------------------------------------------------------
T& operator[] (const size_t i) { return data[i]; } // Index operator, get data at given index. No boundary chek
DynamicArray& operator=(const DynamicArray& other) { // Assignment operator. Make a deep copy
if (this != &other) { // Prevent self-assignment
delete[] data; // Release any previosly existing memory
capacity = numberOfElements = other.numberOfElements;// Take over capacity and number of elements from other container
data = new int[capacity]; // Get new memory, depending on size of other
for (unsigned int k = 0; k < numberOfElements; ++k) // Copy other data
data[k] = other.data[k];
}
return *this;
}
// Extractor and Inserter ------------------------ ---------------------------------------------------------------
friend std::istream& operator >> (std::istream& is, DynamicArray& d) {
std::stringstream ss{};
for (char c{}; (is.get(c) and c != '\n'); ss << c); // Read one line until newline into a stringstream
for (T x{}; ss >> x; d.push_back(x)); // Now extract the data from there
return is;
}
friend std::ostream& operator << (std::ostream& os, const DynamicArray& d) {
for (unsigned int k = 0; k < d.numberOfElements; ++k) // Ultra simple output
os << d.data[k] << ' ';
return os;
}
};
// -----------------------------------------------------------------------------------------------------------
// Very simple 2d array. Derived from standard dynamic array and just defining differen input and output
template <typename T>
class Dynamic2dArray : public DynamicArray<DynamicArray<T>> {
public:
friend std::istream& operator >> (std::istream& is, Dynamic2dArray& d) {
for (DynamicArray<T> temp{}; is >> temp; d.push_back(temp), temp.clear());
return is;
}
friend std::ostream& operator << (std::ostream& os, const Dynamic2dArray& d) {
for (unsigned int k = 0; k < d.numberOfElements; ++k)
os << d.data[k] << '\n';
return os;
}
};
// -----------------------------------------------------------------------------------------------------------
int main() {
// Open the sourcefile and check, if it could be opened
if (std::ifstream sourceFileStream{ "test.txt" }; sourceFileStream) {
// Define 2D array to hold all data and initialize it with all 0
Dynamic2dArray<int> dada;
// Read complete matrix from file
sourceFileStream >> dada;
// Debug output. Show complete Matrix
std::cout << dada;
}
else std::cerr << "\n\nError. Could not open source file\n\n";
}
Basically, everything is the same, somehow . . .

There are a lot of other ways to perform the specific task, but i guess your method is not wrong, and you have just made a simple typing mistake in your second for loop condition. so ill just fix your code for you.
and also you could just input single values at a time as u go.
#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout <<"Reading Start" <<endl;
ifstream rfile("test.txt");
int i,j;
for(i=0;i<6;i++){
for(j=0;j<6;j++){
rfile >> arr1[i][j];
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout <<"\nRead Done" <<endl<<endl;
rfile.close();
}
Output :

Related

Reading in a file that has strings and ints in c++

So I have a sample file that I would like to read in, looking something like:
data 1
5
data 2
0
9
6
6
1
data 3
7
3
2
I basically want to assign each of these to variables I have in a struct, eg. my struct looks like:
struct sample_struct
{ int data1;
double* data2;
double* data3;
};
How do I approach this question?
I think I would be able to do it if I had the sample number of integers following each of the string titles, but like this I have no idea. Please help.
You have to solve 2 problems.
Dynamic memory management.
Detect, where, inwhich section we are and where to store the data.
Number 1 will usually be solved with a std::vector in C++. Raw pointers for owened memory or C-Style arrays are not used in C++.
If you do not want to or are not allowed to the a std::vetor you need to handcraft some dynamic array. I made an example for you.
For the 2nd part, we can simple take the alphanumering string as a separator for different sections of the source file. So, if we see an alpha character, we go to a new section and then store the data in the appropriate struct members.
Input and output in C++ is usually done with the extractor >> and inserter << operator. This allows to read from and write to any kind of stream. And, in C++ we use often object oriented programming. Here, data and methods are packed in one class/struct. Only the class/struct should know, how to read and write its data.
Based on the above thoughts, we could come up with the below solution:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
// Ultra simle dynamic array
struct DynamicDoubleArray {
// Constructor and Destructor
DynamicDoubleArray() { values = new double[capacity]; }; // Allocate default memory
~DynamicDoubleArray() { delete[] values; }; // Release previously allocated memory
// Data
double* values{}; // Here we store the values. This is a dynamic array
int numberOfElements{}; // Number of elements currently existing in dynamic array
int capacity{ 2 }; // Number of elements that could be stored in the dynamic array
void push_back(double v) { // Add a new aelement to our dynamic array
if (numberOfElements >= capacity) { // Check, if we have enough capacity to store the new element
capacity *= 2; // No, we have not. We need more capacity
double* temp = new double[capacity]; // Get new, bigger memory
for (int k = 0; k < numberOfElements; ++k) // Copy old data to new bigger memory
temp[k] = values[k];
delete[] values; // Delete old data
values = temp; // And assign new temp data to our original pointer
}
values[numberOfElements++] = v; // Store new data and increment element counter
}
};
// Our sample struct
struct SampleStruct {
// Data part
int data1{};
DynamicDoubleArray data2{};
DynamicDoubleArray data3{};
// Help functions. We overwrite the inserter and extractor operator
// Extract elements from whatever stream
friend std::istream& operator >> (std::istream& is, SampleStruct& s) {
std::string line{}; // Temporaray storage to hold a complete line
int section = 0; // Section. Where to store the data
while (std::getline(is, line)) {
if (std::isalpha(line[0])) { // If we see an alpha character then we are in the next section
++section; // Now, we will use the next section
continue;
}
switch (section) { // Depending on in which section we are
case 1:
s.data1 = std::stoi(line); // Section 1 --> Store int data
break;
case 2:
s.data2.push_back(std::stod(line)); // Section 2 --> Add/Store double data 2
break;
case 3:
s.data3.push_back(std::stod(line)); // Section 3 --> Add/Store double data 2
break;
default:
std::cerr << "\nError: internal mode error\n";
break;
}
}
return is;
}
// Simple output
friend std::ostream& operator << (std::ostream& os, const SampleStruct& s) {
os << "\nData 1: " << s.data1 << "\nData 2: ";
for (int k = 0; k < s.data2.numberOfElements; ++k)
os << s.data2.values[k] << ' ';
os << "\nData 3: ";
for (int k = 0; k < s.data3.numberOfElements; ++k)
os << s.data2.values[3] << ' ';
return os;
}
};

Using a 2D array for a game map in C++

Software: Visual Studio 2017 Community
Hi, everybody,
I am making a simple 2d console game in C++ (perhaps very simplified Dwarf Fortress if you know it).
And I want a map to be displayed in console with ASCII.
Something like this:
I have a WorldMap class declared in the header file(simplified version).
And I declare a 2d array inside it.
#pragma once
#include <iostream>
class WorldMap
{
public:
WorldMap();
virtual ~WorldMap();
private:
int worldWidth;
int worldHeight;
char worldMap; // Declare a variable that will hold all the characters for the map
};
And then define it in the .cpp file:
#include "WorldMap.h"
#include <algorithm>
WorldMap::WorldMap()
{
worldWidth = 50;
worldHeight = 50;
worldMap[50][50]; // Define the map array
// And then here I will also somehow need to be able to fill the whole map with '.' symbols, and so on
}
So that is the basic idea of what I am trying to achieve. The reason why I can't define the array size immediately is because I want to be able to choose the size of the map when the map is created.
I have already tried:
The code above.
Error:
error C2109: subscript requires array or pointer type
Declaring 2d array as char worldMap[][]; and then defining it as worldMap[50][50]; .
Error:
error C2087: 'worldMap': missing subscript
warning C4200: nonstandard extension used: zero-sized array in struct/union
message : This member will be ignored by a defaulted constructor or copy/move assignment operator
Declaring 2d array as char worldMap[worldWidth][worldHeight];, expecting that when the object is created, the width and height variables will be defined first, and then they will define the array.
Error:
error C2327: 'WorldMap::worldWidth': is not a type name, static, or enumerator
error C2065: 'worldWidth': undeclared identifier
error C2327: 'WorldMap::worldHeight': is not a type name, static, or enumerator
error C2065: 'worldHeight': undeclared identifier
Using char* worldMap; and char** worldMap, but so far I can't even understand how double pointer works, yet char* worldMap actually works with a 1D array without errors, until I start accessing values of the elements in the array.
I suppose a workaround would be to use a string or 1D char array and when displaying it just use mapWidth to end line each 50 characters for example, which will give the same result. But I feel like that's not a good way to achieve this since I will need to access x and y coords of this map and so on.
I guess what I am asking is:
What's the best way of declaring a 2d array for a class and then defining it in the object?
What's the best way to store a map for such a console game? (Not necessarily using arrays)
Thank you for reading. I will really appreciate any help, even just ideas and tips might push me in the right direction :)
What's the best way of declaring a 2d array for a class and then defining it in the object?
What's the best way to store a map for such a console game? (Not necessarily using arrays)
This is not "the best way" but it's one way of doing it.
Create a class wrapping a 1D std::vector<char>.
Add operator()s to access the individual elements.
Add misc. other support functions to the class, like save() and restore().
I've used your class as a base and tried to document what it's doing in the code: If some of the functions I've used are unfamiliar, I recommend looking them up at https://en.cppreference.com/ which is an excellent wiki that often has examples of how to use the particular function you read about.
#include <algorithm> // std::copy, std::copy_n
#include <filesystem> // std::filesystem::path
#include <fstream> // std::ifstream, std::ofstream
#include <iostream> // std::cin, std::cout
#include <iterator> // std::ostreambuf_iterator, std::istreambuf_iterator
#include <vector> // std::vector
class WorldMap {
public:
WorldMap(unsigned h = 5, unsigned w = 5) : // colon starts the initializer list
worldHeight(h), // initialize worldHeight with the value in h
worldWidth(w), // initialize worldWidth with the value in w
worldMap(h * w, '.') // initialize the vector, size h*w and filled with dots.
{}
// Don't make the destructor virtual unless you use polymorphism
// In fact, you should probably not create a user-defined destructor at all for this.
//virtual ~WorldMap(); // removed
unsigned getHeight() const { return worldHeight; }
unsigned getWidth() const { return worldWidth; }
// Define operators to give both const and non-const access to the
// positions in the map.
char operator()(unsigned y, unsigned x) const { return worldMap[y*worldWidth + x]; }
char& operator()(unsigned y, unsigned x) { return worldMap[y*worldWidth + x]; }
// A function to print the map on screen - or to some other ostream if that's needed
void print(std::ostream& os = std::cout) const {
for(unsigned y = 0; y < getHeight(); ++y) {
for(unsigned x = 0; x < getWidth(); ++x)
os << (*this)(y, x); // dereference "this" to call the const operator()
os << '\n';
}
os << '\n';
}
// functions to save and restore the map
std::ostream& save(std::ostream& os) const {
os << worldHeight << '\n' << worldWidth << '\n'; // save the dimensions
// copy the map out to the stream
std::copy(worldMap.begin(), worldMap.end(),
std::ostreambuf_iterator<char>(os));
return os;
}
std::istream& restore(std::istream& is) {
is >> worldHeight >> worldWidth; // read the dimensions
is.ignore(2, '\n'); // ignore the newline
worldMap.clear(); // empty the map
worldMap.reserve(worldHeight * worldWidth); // reserve space for the new map
// copy the map from the stream
std::copy_n(std::istreambuf_iterator<char>(is),
worldHeight * worldWidth, std::back_inserter(worldMap));
return is;
}
// functions to save/restore using a filename
bool save(const std::filesystem::path& filename) const {
if(std::ofstream ofs(filename); ofs) {
return static_cast<bool>(save(ofs)); // true if it suceeded
}
return false;
}
bool restore(const std::filesystem::path& filename) {
if(std::ifstream ifs(filename); ifs) {
return static_cast<bool>(restore(ifs)); // true if it succeeded
}
return false;
}
private:
unsigned worldHeight;
unsigned worldWidth;
// Declare a variable that will hold all the characters for the map
std::vector<char> worldMap;
};
Demo
There is no best way to do anything*. It's what works best for you.
From what I understand you want to make a dynamic 2D arrays to hold your char of world map. You have a lot of options to do this. You can have a worldMap class nothing wrong with that. If you want dynamic 2D arrays just make functions out of this kind of logic.
#include <iostream>
#include <vector>
int main() {
int H = 10, W = 20;
char** map = NULL; //This would go in your class.H
//Make a function to allocate 2D array
map = new char* [H];
for (int i = 0; i < H; i++) {
map[i] = new char[W];
}
//FILL WITH WHATEVER
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
map[i][j] = 'A';
}
}
//do what ever you want like normal 2d array
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
std::cout << map[i][j] << " ";
}
std::cout << std::endl;
}
//Should always delete when or if you want to make a new one run time
for (int i = 0; i < H; i++)
delete[] map[i];
delete[] map;
map = NULL;
//Also you can use vectors
std::cout << "\n\n With vector " << std::endl;
std::vector<std::vector<char>> mapV;
//FILL WITH WHATEVER
for (int i = 0; i < H; i++) {
std::vector<char> inner;
for (int j = 0; j < W; j++) {
inner.push_back('V');
}
mapV.push_back(inner);
}
//do what ever you want kind of like a normal array
//but you should look up how they really work
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
std::cout << mapV[i][j] << " ";
}
std::cout << std::endl;
}
mapV.clear();
return 0;
}

C++: Setters and Getters for Arrays

I am struggling to find the correct format for initializing a (private) array within a class and getting/setting the values from outside the class.
My code is semi-functional, but feels awkward in incorrectly formatted.
It is returning only the first element of the array, I want it to return all the contents. Read code comments for additional details.
Note: This is (a very small part of) a project I am working on for school -- an array must be used, not a vector or list.
student.h
class Student {
public:
// Upon researching my issue, I read suggestions on passing pointers for arrays:
void SetDaysToCompleteCourse(int* daysToCompleteCourse[3]);
int* GetDaysToCompleteCourse(); // Ditto # above comment.
private:
int daysToCompleteCourse[3];
student.cpp
#include "student.h"
void Student::SetDaysToCompleteCourse(int* daysToCompleteCourse) {
// this->daysToCompleteCourse = daysToCompleteCourse; returns error (expression must be a modifiable lvalue)
// Feels wrong, probably is wrong:
this->daysToCompleteCourse[0] = daysToCompleteCourse[0];
this->daysToCompleteCourse[1] = daysToCompleteCourse[1];
this->daysToCompleteCourse[2] = daysToCompleteCourse[2];
}
int* Student::GetDaysToCompleteCourse() {
return daysToCompleteCourse;
}
ConsoleApplication1.cpp
#include "pch.h"
#include <iostream>
#include "student.h"
int main()
{
Student student;
int daysToCompleteCourse[3] = { 1, 2, 3 };
int* ptr = daysToCompleteCourse;
student.SetDaysToCompleteCourse(ptr);
std::cout << *student.GetDaysToCompleteCourse(); // returns first element of the array (1).
}
I gave this my best shot, but I think I need a nudge in the right direction.
Any tips here would be greatly appreciated.
I would say:
// student.h
class Student
{
public:
// If you can, don't use numbers:
// you have a 3 on the variable,
// a 3 on the function, etc.
// Use a #define on C or a static const on C++
static const int SIZE= 3;
// You can also use it outside the class as Student::SIZE
public:
void SetDaysToCompleteCourse(int* daysToCompleteCourse);
// The consts are for "correctness"
// const int* means "don't modify this data" (you have a setter for that)
// the second const means: this function doesn't modify the student
// whithout the const, student.GetDaysToCompleteCourse()[100]= 1 is
// "legal" C++ to the eyes of the compiler
const int* GetDaysToCompleteCourse() const; // Ditto # above comment.
Student()
{
// Always initialize variables
for (int i= 0; i < SIZE; i++) {
daysToCompleteCourse[i]= 0;
}
}
private:
int daysToCompleteCourse[SIZE];
// On GCC, you can do
//int daysToCompleteCourse[SIZE]{};
// Which will allow you not to specify it on the constructor
};
// student.cpp
void Student::SetDaysToCompleteCourse(int* newDaysToCompleteCourse)
{
// It's not wrong, just that
// this->daysToCompleteCourse[0] = daysToCompleteCourse[0];
// use another name like newDaysToCompleteCourse and then you can suppress this->
// And use a for loop
for (int i= 0; i < SIZE; i++) {
daysToCompleteCourse[i]= newDaysToCompleteCourse[i];
}
}
const int* Student::GetDaysToCompleteCourse() const
{
return daysToCompleteCourse;
}
// main.cpp
#include <iostream>
std::ostream& operator<<(std::ostream& stream, const Student& student)
{
const int* toShow= student.GetDaysToCompleteCourse();
for (int i= 0; i < Student::SIZE; i++) {
stream << toShow[i] << ' ';
}
return stream;
}
int main()
{
Student student;
int daysToCompleteCourse[3] = { 1, 2, 3 };
// You don't need this
//int* ptr = daysToCompleteCourse;
//student.SetDaysToCompleteCourse(ptr);
//You can just do:
student.SetDaysToCompleteCourse(daysToCompleteCourse);
// On C++ int* is "a pointer to an int"
// It doesn't specify how many of them
// Arrays are represented just by the pointer to the first element
// It's the FASTEST and CHEAPEST way... but you need the SIZE
const int* toShow= student.GetDaysToCompleteCourse();
for (int i= 0; i < Student::SIZE; i++) {
std::cout << toShow[i] << ' ';
// Also works:
//std::cout << student.GetDaysToCompleteCourse()[i] << ' ';
}
std::cout << std::endl;
// Or you can do: (because we defined operator<< for a ostream and a Student)
std::cout << student << std::endl;
}
You can check out it live here: https://ideone.com/DeJ2Nt

how can i save an unknow number integers from a .txt file into an array

I have generated a data.txt file that contains a huge number of integers into two columns.
How can I save these integers into arrays?
You can find the data.txt here if that helps. Sample:
600000
523887 283708
231749 419866
293707 273512
296065 215334
233447 207124
264381 460210
374915 262848
449017 329022
374111 151212
2933 496970
I have tried this but for some reason its not working..
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input("data-for-union-find.txt");
int i=0;
float a;
int size=0;
size=i/2;
while (input >> a)
{i++;
}
int *x=new int[size];
int *y=new int[size+1];
for(int j=0;j<(size+1);j++)
{
input>>x[j];
input>>y[j];
cout<<x[j]<<" "<<y[j]<<" "<<j<<endl;
return 0;
}
}
To add more elements to an array, beyond its capacity, you have to:
Allocate a new, larger array.
Copy all elements from old array to new array.
Delete old array.
Append new element(s).
A safer solution is to use std::vector and the push_back method.
If you have a large amount of data, you may want to declare the std::vector with a large size to reduce the number of reallocations.
I would write directly into a single container which avoids allocations:
#include <deque>
#include <iostream>
#include <sstream>
template <typename Sequence>
inline int xvalue(const Sequence& data, std::size_t index) {
return data[2*index];
}
template <typename Sequence>
inline int yvalue(const Sequence& data, std::size_t index) {
return data[2*index + 1];
}
int main() {
std::istringstream stream(""
"600000\n"
"523887 283708\n"
"231749 419866\n"
"293707 273512\n"
"296065 215334\n"
"233447 207124\n"
"264381 460210\n"
"374915 262848\n"
"449017 329022\n"
"374111 151212\n"
"2933 496970\n");
// Get rid of the suspicious first value:
int suspicious;
stream >> suspicious;
// Use a sequence, which avoids allocations
std::deque<int> data
// Read x,y:
int x;
int y;
while(stream >> x >> y) {
data.push_back(x);
data.push_back(y);
}
// Display:
for(std::size_t i = 0; i < data.size() / 2; ++i)
std::cout << "x = " << xvalue(data, i) << ", y = " << yvalue(data, i) << '\n';
// If you need contiguous memory
std::vector<int> contiguous(data.begin(), data.end());
}

Insert an array of tables into one table SQLite C/C++

I made my own database format, and it sadly required too much memory and the size of it got horrendous and upkeep was horrible.
So I'm looking for a way to store an array of a struct that's in an object into a table.
I'm guessing I need to use a blob, but all other options are welcome. An easy way to implement a blob would be helpful as well.
I've attached my saving code and related structures(Updated from my horrible post earlier)
#include "stdafx.h"
#include <string>
#include <stdio.h>
#include <vector>
#include "sqlite3.h"
using namespace std;
struct PriceEntry{
float cardPrice;
string PriceDate;
int Edition;
int Rarity;
};
struct cardEntry{
string cardName;
long pesize;
long gsize;
vector<PriceEntry> cardPrices;
float vThreshold;
int fav;
};
vector<cardEntry> Cards;
void FillCards(){
int i=0;
int j=0;
char z[32]={0};
for(j=0;j<3;j++){
cardEntry tmpStruct;
sprintf(z, "Card Name: %d" , i);
tmpStruct.cardName=z;
tmpStruct.vThreshold=1.00;
tmpStruct.gsize=0;
tmpStruct.fav=1;
for(i=0;i<3;i++){
PriceEntry ss;
ss.cardPrice=i+1;
ss.Edition=i;
ss.Rarity=i-1;
sprintf(z,"This is struct %d", i);
ss.PriceDate=z;
tmpStruct.cardPrices.push_back(ss);
}
tmpStruct.pesize=tmpStruct.cardPrices.size();
Cards.push_back(tmpStruct);
}
}
int SaveCards(){
// Create an int variable for storing the return code for each call
int retval;
int CardCounter=0;
int PriceEntries=0;
char tmpQuery[256]={0};
int q_cnt = 5,q_size = 256;
sqlite3_stmt *stmt;
sqlite3 *handle;
retval = sqlite3_open("sampledb.sqlite3",&handle);
if(retval)
{
printf("Database connection failed\n");
return -1;
}
printf("Connection successful\n");
//char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)";
char create_table[] = "CREATE TABLE IF NOT EXISTS Cards (CardName TEXT, PriceNum NUMERIC, Threshold NUMERIC, Fav NUMERIC);";
retval = sqlite3_exec(handle,create_table,0,0,0);
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(handle) );
for(CardCounter=0;CardCounter<Cards.size();CardCounter++){
char Query[512]={0};
for(PriceEntries=0;PriceEntries<Cards[CardCounter].cardPrices.size();PriceEntries++){
//Here is where I need to find out the process of storing the vector of PriceEntry for Cards then I can modify this loop to process the data
}
sprintf(Query,"INSERT INTO Cards VALUES('%s', %d, %f, %d)",
Cards[CardCounter].cardName.c_str(),
Cards[CardCounter].pesize,
Cards[CardCounter].vThreshold,
Cards[CardCounter].fav); //My insert command
retval = sqlite3_exec(handle,Query,0,0,0);
if(retval){
printf( "Could not prepare statement: %s\n", sqlite3_errmsg(handle) );
}
}
// Insert first row and second row
sqlite3_close(handle);
return 0;
}
I tried googling but my results didn't suffice.
You have two types here: Cards and PriceEntries. And for each Card there can be many PriceEntries.
You can store Cards in one table, one Card per row. But you're puzzled about how to store the PriceEntries, right?
What you'd normally do here is have a second table for PriceEntries, keyed off a unique column (or columns) of the Cards table. I guess the CardName is unique to each card? Let's go with that. So your PriceEntry table would have a column CardName, followed by columns of PriceEntry information. You'll have a row for each PriceEntry, even if there are duplicates in the CardName column.
The PriceEntry table might look like:
CardName | Some PE value | Some other PE value
Ace | 1 | 1
Ace | 1 | 5
2 | 2 | 3
and so on. So when you want to find the array of PriceEntries for a card, you'd do
select * from PriceEntry where CardName = 'Ace'
And from the example data above you'd get back 2 rows, which you could shove into an array (if you wanted to).
No need for BLOBs!
This is a simple serialization and deserialization system. The class PriceEntry has been extended with serialization support (very simply). Now all you have to do is serialize a PriceEntry (or a set of them) to binary data and store it in a blob column. Later on, you get the blob data and from that deserialize a new PriceEntry with the same values. An example of how it is used is given at the bottom. Enjoy.
#include <iostream>
#include <vector>
#include <string>
#include <cstring> // for memcpy
using std::vector;
using std::string;
// deserialization archive
struct iarchive
{
explicit iarchive(vector<unsigned char> data)
: _data(data)
, _cursor(0)
{}
void read(float& v) { read_var(v); }
void read(int& v) { read_var(v); }
void read(size_t& v) { read_var(v); }
void read(string& v) { read_string(v); }
vector<unsigned char> data() { return _data; }
private:
template <typename T>
void read_var(T& v)
{
// todo: check that the cursor will not be past-the-end after the operation
// read the binary data
std::memcpy(reinterpret_cast<void*>(&v), reinterpret_cast<const void*>(&_data[_cursor]), sizeof(T));
// advance the cursor
_cursor += sizeof(T);
}
inline
void
read_string(string& v)
{
// get the array size
size_t sz;
read_var(sz);
// get alignment padding
size_t padding = sz % 4;
if (padding == 1) padding = 3;
else if (padding == 3) padding = 1;
// todo: check that the cursor will not be past-the-end after the operation
// resize the string
v.resize(sz);
// read the binary data
std::memcpy(reinterpret_cast<void*>(&v[0]), reinterpret_cast<const void*>(&_data[_cursor]), sz);
// advance the cursor
_cursor += sz + padding;
}
vector<unsigned char> _data; // archive data
size_t _cursor; // current position in the data
};
// serialization archive
struct oarchive
{
void write(float v) { write_var(v); }
void write(int v) { write_var(v); }
void write(size_t v) { write_var(v); }
void write(const string& v) { write_string(v); }
vector<unsigned char> data() { return _data; }
private:
template <typename T>
void write_var(const T& v)
{
// record the current data size
size_t s(_data.size());
// enlarge the data
_data.resize(s + sizeof(T));
// store the binary data
std::memcpy(reinterpret_cast<void*>(&_data[s]), reinterpret_cast<const void*>(&v), sizeof(T));
}
void write_string(const string& v)
{
// write the string size
write(v.size());
// get alignment padding
size_t padding = v.size() % 4;
if (padding == 1) padding = 3;
else if (padding == 3) padding = 1;
// record the data size
size_t s(_data.size());
// enlarge the data
_data.resize(s + v.size() + padding);
// store the binary data
std::memcpy(reinterpret_cast<void*>(&_data[s]), reinterpret_cast<const void*>(&v[0]), v.size());
}
vector<unsigned char> _data; /// archive data
};
struct PriceEntry
{
PriceEntry()
{}
PriceEntry(iarchive& in) // <<< deserialization support
{
in.read(cardPrice);
in.read(PriceDate);
in.read(Edition);
in.read(Rarity);
}
void save(oarchive& out) const // <<< serialization support
{
out.write(cardPrice);
out.write(PriceDate);
out.write(Edition);
out.write(Rarity);
}
float cardPrice;
string PriceDate;
int Edition;
int Rarity;
};
int main()
{
// create a PriceEntry
PriceEntry x;
x.cardPrice = 1;
x.PriceDate = "hi";
x.Edition = 3;
x.Rarity = 0;
// serialize it
oarchive out;
x.save(out);
// create a deserializer archive, from serialized data
iarchive in(out.data());
// deserialize a PriceEntry
PriceEntry y(in);
std::cout << y.cardPrice << std::endl;
std::cout << y.PriceDate << std::endl;
std::cout << y.Edition << std::endl;
std::cout << y.Rarity << std::endl;
}