How to read from file with a function?

Hello, I tried browsing the web and looking at different places, but I can't figure out how to write a function that could read from text file. Basically what I need is to move what I wrote in main(); into its separate function and that function would need to be able to read from file, but I have no idea how to do that.
Also before anyone ask why I'am not using arrays or structures with this, It's because thats the part of the exercise, to give you more context:
Make a program that could find the heaviest object out of the list. Also find how many objects there are that are at least two times or more lighter than the heaviest.
DO NOT use any kind of arrays or data structures.
Write a separate function to find that object.
DO NOT use division to find lighter objects.
Write a separate function for finding lighter objects.
DO NOT use any sentences for work with console. ( Everything must be done by entering data into the file ).

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 <cmath>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream input ("U2.txt"); //input file (name)
    ofstream output ("U2rez.txt");//output file (name)
    int n; //Number in the first line of the file represent total amount
    input >> n; //of different variables the program will need to read

    int maximum;//Program takes the second variable from the file
    input >> maximum;//and sets it as the "heaviest" object
    int var1;//int for the next variable
    for (int i=0; i<n; i++){ //for cycle set to repeat itself n-times
        input >> var1; //with each cycle we take the next variable from file
        if (var1>maximum){//and compare it with the maximum one to see if its "heavier"
            maximum=var1;//if it is, "maximum" changes its value and the cycle repeats itself
        }
    }
    

    input.close();
    output.close();
    return 0;
}
Last edited on
Note that you have things that you don't need/use.

Doing things in a function could be trivial:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>

void magic()
{
    std::ifstream input ("U2.txt");
    int n;
    input >> n;
    int maximum;
    input >> maximum;
    int var1;
    for (int i=0; i<n; i++){
        input >> var1;
        if (var1>maximum){
            maximum=var1;
        }
    }
    input.close();
}

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

For more, see: http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Hello wuwy, getting some variable to/into a function is easy to handle if you know about 'passing by reference'.

The standard way passing variables/values to a function is 'passing by value'. That means that all arguments will be copied into a function.

1
2
3
4
int square( int val)
{
    return val * val;
}

Here variable 'val' will be passed as a copy, and also the returned value will be passed as a copy.

But here:
1
2
3
4
void square( int & val)
{
    val *=  val;
}

The value will be passed as a reference, which means that, roughly spoken, val inside the function will be the same that is passed to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int square( int val) { return val * val; }

void square2( int& val ) { val *= val; }

int main()
{
    int a = 3;
    square( a )
    std::cout << a;  // 3
    square2(a);
    std::cout << a;  // 9
}


So you can use the behavior of 'passing by reference' to getting some variables out of a function without needing passing them by 'return'.
Last edited on
@keskiverto ah, if you are talking about output file, I only half wrote this program and decided to ask for help with the function bit before continuing, so it will come in later. The extra libraries are there because I just use template I wrote earlier ( as I'am lazy ) and will delete them later. And I can just write the fstream in the function? I thought it might be something harder, thanks for clearing that up.

@nuderobmonkey I read about passing by reference, but didn't look too much into it, as I only this week started actually working ( or at least trying to ) with functions. But I guess I will have to look into it sooner or later.
There are many ways to pass data. Lets showcase some more:
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
#include <fstream>
#include <iostream>

int maxfromstream( std::istream& input )
{
    int maximum = 0;
    int n;
    input >> n;
    input >> maximum;
    int var1;
    for (int i=0; i<n; i++){
        input >> var1;
        if (var1>maximum){
            maximum=var1;
        }
    }
    return maximum;
}

int readmax( const char* name ) {
  std::ifstream file( name );
  if ( file ) {
    return maxfromstream( file );
  } else {
    return 0;
  }
}

int main() {
  int result = readmax( "U2.txt" );
  std::cout << result << '\n';
  return 0;
}
Last edited on
I don't need to use "std" if I have namespace right?
yes, but that (used to be best practice) has become (bad practice) due to the size of the std namespace and potential for issues. You can read a lot of threads on that or google on it for more info.
yes, but that (used to be best practice)

No, "using namespace std;" was never a "best" practice, it was at best an "accepted" practice to allow existing pre-standard C++ code to compile with a standard C++ compiler without a lot of tweaking. But it was always recommended not to use the "using namespce std;" clause on new code.

ok, so it's not something I should worry myself in intro course then.
closed account (E0p9LyTq)
ok, so it's not something I should worry myself in intro course then.

The more code you write adding using namespace std; the harder it will be to break the habit when you need to.

I used to use it at the beginning. Then one day I decided to stop adding it and always use std::. Now I type it without even thinking.
I guess, but I want to fully wrap my head around all of this before taking it further
So long as it doesn't matter for someone, it's no problem using namespace xxx. I, for example, used this mostly at the begin of my learning how to code. But later, when I needed to use libraries other than from std, it got messy. I read my own code and was often unsure from which library it came. Also, consider of other readers than yourself: You would make them harder reading your code if you dumping all your stuff in the default namespace.
IMO, Beginners especially should not be taught using namespace std.

To a beginner, the difference is that he or she learns that cout is spelled std::cout and the like, and that he or she needs not the boilerplate phrase using namespace std at the top of every program.

The advantage is that using full names sidesteps a slew of subtle portability issues. This reduces the chance of writing code that compiles on your machine but not on your professor's.

More experienced C++ programmers can perhaps get away with using directives, but beginners are apt to encounter problems, because they might not know which names are present in the standard library, nor understand any of the complicating factors.

This thread over at the Core Guidelines seems representative of expert opinion:
https://github.com/isocpp/CppCoreGuidelines/issues/725
Last edited on
Topic archived. No new replies allowed.