Create header file for string function

Hey guys I have a function that returns a string fine on its own, but when I create a header file for it and try to compile it gives me an error in the header file that says "error: 'string' does not name a type. What is wrong with my header file.

Function that returns a string, this works fine when I comment out line 6, but I get an error when I do include it.

#include <fstream>
#include <string>
#include <string.h>
#include <iostream>
#include <string.h>
//#include "getBoard.h"

using namespace std;

string File(){
ifstream readFile;
readFile.open("ReadTest.txt");
size_t marker;
string data, line, number="";

if(readFile.is_open()){

while(readFile.good()){
getline(readFile, line);
data = data +line;
}
}
else{
cout << "error opening file \n";
return "Error";
}

marker = data.find('a');
marker = marker +3;
number = data.substr(marker, 81);
cout << number << "\n";
return number;
}

int main(){
string value = File();
cout << value <<"\n";
return 0;
}

and here is the header file i wrote for the above program

#ifndef GETBOARD_H
#define GETBOARD_H
string File();
#endif
To address your problem, you did not include <string> in your header file, so it doesn't know what "string" is. As far as your compiler is concerned, it does not exist.

As far as the rest of your code goes, you are using the deprecated version of <string>... remove the ".h" suffix. You also included it three times. Also, don't define all your functions above the main function... it can lead to some errors about your functions being undefined. Use function prototypes and put them below the main function.
Thanks that worked and I was just wondering how can the program give me errors about functions being undefined if I define all the functions above the main. Won't compiler see the function definitions before it sees that the main is calling upon them so there won't ever be a problem?
closed account (DSLq5Di1)
Each file is compiled seperately, "getBoard.h" does not know it is being included in another file, or that there are headers included above it.
To answer your question about functions... say I had a program like this...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using std::cout;

int A() {
    return (int)(B());
}

double B() {
    return 5.34;
}

int main(int argc, char** argv) {
   cout << A();
   return 0;
}


This would give you an error because A() is calling the B() function before it is defined. This may seem like a very simple example to you, but it can lead to problems. Just get in the habit of using function prototypes and defining your functions elsewhere. You could keep your functions above the main function if you want, but you would need to at least put the function prototypes above them.

http://www.cplusplus.com/doc/tutorial/functions2/

Scroll down to "Declaring Functions".
Okay makes sense now thanks
Topic archived. No new replies allowed.