Function won't write out whole array.
Jan 2, 2016 at 2:57pm UTC
When I call my function write and I input my array in to the parameters, I am unable to find the size of the array. Thus I can not figure out how many times U need to write or take in. Is there possible any other way to figure this out?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#pragma once
#ifndef SAVE_H
#define SAVE_H
#include <fstream>
#include <string>
template <typename special> class save {
private :
int counter;
int size;
std::fstream A;
public :
save(std::string txt);
save();
~save();
void read(std::string txt, special argIn[]) {
A.open(txt, std::fstream::in);
if (A.fail()) {
A.open(txt, std::fstream::out);
}
else {
counter = 0;
while (!A.eof()) {
counter++;
A >> argIn[counter];
}
}
A.close();
}
void write(std::string txt, special Z[]) {
size = sizeof (Z) / sizeof (Z[0]);
cout << size;
A.open(txt, std::fstream::out | std::fstream::trunc);
for (unsigned int i = 0; i < size; i++) {
A << Z[i] << std::endl;
}
}
void check(special var1, special var2) {
return (var1 > var2) ? var1 : var2;
}
};
template <typename special>
inline save<special>::save(std::string txt)
{
A.open(txt, std::fstream::out);
A << "First number = 1" ;
A.close();
}
template <typename special>
inline save<special>::~save()
{
}
template <typename special>
inline save<special>::save()
{
}
#endif
Jan 2, 2016 at 3:20pm UTC
I don't know what you need the class for, but you can take the arrays by reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
template <typename value_type, std::size_t size>
void read(const std::string& file_name, value_type(&values)[size])
{
std::ifstream in(file_name);
std::size_t count = 0;
while (count < size && in >> values[count])
++count;
}
template <typename value_type, std::size_t size>
void write(const std::string& file_name, value_type(&values)[size])
{
std::ofstream out(file_name);
std::size_t count = 0;
while (count < size)
out << values[count++] << '\n' ;
}
By default, arrays are passed as a pointer to the first element.
Topic archived. No new replies allowed.