Using a function to increment every number in an array by 1

I want the program to read in a set of numbers from a file, increment each number by 1, then output to a different file. Can somebody please tell me what I am doing wrong? I am trying to use the function "doubler" to increment it by 1.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <math.h>
#include <iomanip>
#include <fstream>
#include <cstdlib>


using namespace std;

void doubler(double element);

int main()
{
    string filenamein;
    string filenameout;
    ifstream fin;
    ofstream fout;
    int i;
    char yesno('N');
    
    do{
    cout << "Enter the input file name: "<< endl;
    cin >> filenamein;
    
    fin.open(filenamein.c_str());
        if (fin.fail())
    {
            {
        cerr << "File not found" << endl;
            cerr << "Would you like to try again? Type Y for yes and N to exit" << endl;
            cin >> yesno;
        }
    
        
        if (yesno == 'N')
        {
            cerr << "Exiting program..." << endl;
            exit(1);
        }
    }
        
        }while (yesno == 'Y');
            
    cout << "Filename opened successfully" << endl;
    
    int counter(0);
    double array[50];
    i=0;
    while (fin>>array[i])
    {
        i++;
        counter++;
    }
    
    for (i=0; i<counter-1; i++)
    {
        doubler(array[i]);
    }
    
    fin.close();
    
    cout <<  "Enter outfile file name: " << endl;
    cin >> filenameout;
    
    fout.open(filenameout.c_str());
    
    if (fout.fail())
    {
        cerr << "File could not be opened" << endl;
        cerr << "Exiting program... " << endl;
        exit(1);
    }
    
    for (i=0; i<counter-1; i++)
    {
        
        fout << array[i] << endl;
    }
    fout.close();
    
    
    
    
    
    
  return 0;
}


void doubler(double element)
{
    element++;

        return;
}
Last edited on
What part is not working?
Two errors (I think):

(1) Lines 55 and 74 should both be
for (i=0; i<counter; i++)

(2) Scalar arguments in C++ are, by default, passed by value. This means that you can change element to your heart's content in line 92, but, as it stands, it won't get passed back.

Instead, if you want to retain a void function then pass element by reference by changing line 90 to
void doubler(double &element)
and remember to change your function prototype in line 10 similarly.

(Alternatively, you could change the return type of the function to double and return this new value if you preferred.)



While you are at it, it would be good to change
#include <math.h>
to the more modern
#include <cmath>
(Not that you are actually using it yet.)
Last edited on
Topic archived. No new replies allowed.