Dec 11, 2015 at 2:39pm UTC
Hello again.
Got great help here so i have been having a different problem i cant really solve for the life of me.
So i got my code to work in the same file but now i want to make a seperate header file and .cpp file for my function. This is what i got so far
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include "function1.h"
using namespace std;
int main()
{
if (IsFileSorted())
{
cout << "Filen är sorterad." << endl;
}
else
{
cout << "Filen är osorterad." << endl;
}
return 0;
}
function1.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include "functions.h"
bool IsFileSorted()
{
numbers.open("testar1" );
if (!numbers.is_open())
cout << "The file did not open correctly" << endl;
numbers >> oldnr;
while (!numbers.eof())
{
numbers >> newnr;
if (oldnr > newnr)
return false ;
oldnr = newnr;
}
return true ;
}
function1.h
1 2 3 4 5 6 7
#include <fstream>
bool IsFileSorted()
ifstream numbers;
int newnr;
int oldnr;
The error code i am currently getting with this code is
"function1.h:5:1: error: expected initializer before ‘ifstream’
ifstream numbers;"
and
"main.cpp:7:20: error: ‘IsFileSorted’ was not declared in this scope
if (IsFileSorted())"
Last edited on Dec 11, 2015 at 2:40pm UTC
Dec 11, 2015 at 2:42pm UTC
Line 3 in function1.h should be followed by a semi-colon.
Lines 5, 6 and 7 should not be in the header file.
Also, google "include guards"
Last edited on Dec 11, 2015 at 2:43pm UTC
Dec 11, 2015 at 4:07pm UTC
Hmm okay, i think i have missunderstood the use of headers. I thought you could add all of your variables in there but it should just be the function and nothing else? I will give it a try soon-ish and respond back with how it went.
Ah yeah i read about guards in the tutorial on this site, will add them asap.
Thanks. :)
Dec 11, 2015 at 4:55pm UTC
Another view for using header files:
http://www.learncpp.com/cpp-tutorial/19-header-files/
Dec 11, 2015 at 9:39pm UTC
Thanks for the reply guys, helped a lot and now i understand it! :)