Passing Read values from a function to another

I'm trying to pass all read values into a converter and have it convert each individual number into Mins/secs, but I'm not sure how to pass the Read values into another function.

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
  #include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int inFile ();

int main()
{
  inFile();
    
    return 0;
}

int inFile()
{
  int songLength;
  ifstream inFile;
  inFile.open("songs.dat");
  if (!inFile)
{
    cout << "\nError opening file\n";
}

  //intial Read
  while (inFile >> songLength)
	cout << songLength << endl;
  
  inFile.close();
}
One way to do it.
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
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int inFile();

void convert(int songLenth, int& minutes, int& seconds)
{
  // TO DO convert to minutes and seconds and store the
  // values in minutes and seconds

}

int main()
{
  inFile();

  return 0;
}

int inFile()
{
  int songLength;
  ifstream inFile;
  inFile.open("songs.dat");
  if (!inFile)
  {
    cout << "\nError opening file\n";
    return -1;
  }
  int minutes = 0, seconds = 0;
  //intial Read
  while (inFile >> songLength)
  {
    cout << songLength << endl;
    convert(songLength, minutes, seconds);
    cout << "Minutes: " << minutes << "\n";
    cout << "Seconds: " << seconds << "\n";
  }
  // inFile.close(); not necessary
  //return some value here
}

the function inFile will not compile properly, it is suppose to return an int value but it actually doesn't.

You may use the return value to pass the read value back to main, you may use a vector from STL to store your data.

I cannot see the part in which you convert data in min/sec, but if you don't read data in min/sec even this should be putted in a different function.

I would do something like

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
void read_file(std::string fileName, std::vector<double> lengths);

int main();
std::vector<double> len;
std::string fileName;
// you provide your program a way to set the input file name
read_file(fileName,len);

// do interesting stuff with the vector len 
return 0;
}

void read_file(std::string fileName, std::vector<double> lengths){
  std::ifstream inFile(fileName);
double songLength;
  if (!inFile.open())
{
    cout << "\nError opening file\n";
}

  //intial Read
  while (inFile >> songLength){
	len.push_back(songLength);
        std::cout << songLength << std::endl;
  }
  inFile.close();
}
My conversion

1
2
3
4
5
void convert(int songLength, int &minute, int &seconds)
{
    minute = (songLength % 3600) / 60;  // Minute component
    seconds = songLength % 60;          // Second component
}
Last edited on
Topic archived. No new replies allowed.