Can you load code from another file

If i were to just write code in a different file on the same project, could i load that file in and have it read that. I have a split choice and both will have a continuation of a story beneath. The only way i know to do that is to have a huge story underneath an if command. That would be ugly wouldn't it?
You could read from a text file instead of hard-coding all the text.
How would i do that, and will it process as code?
#include
is what you're looking for. It injects the contents of the specified file into the current source file.
Naaa not the compiler directive or whatever that is called, basically i want it to look like this.

#include <iostream>
using namespace std;

int main()
{
int choice
cout << "What choice";
cin >> ("%d", choice);

if ( choice == 1)
{
//This is where i want code to be put so it looks better
}

else if ( choice == 2)
{
//This is where i want code to be put so it looks better
}
}

I hope that shows what i mean...
Well, in theory you could make two functions, one for each choice.
However, if this is some sort of text adventure or something, then you need to think of a better concept anyway, as you can't just keep splitting up things indefinitely.
Instead, you can generate a game world with various elements and actors that you can move around in and interact with by the use of commands.
Im just starting with C++ and im trying to get a concept of coding. I love it, and i will be doing that some day. As for now, i wish to do this game. I am not splitting things up, this is the only time it splits. But if you think about it, this is kind of how Fallout games are, many path splits. Obviously im not going to go that far, but that is the idea.

For the two functions, can they be on different files and still load into the main one?
Yes. If you do a bit of research, you should be able to have a multi-file project working with no problems.
ya the problem is this is my research. I have been looking for ways for a while.
I'm not sure why everyone here is suggesting multiple source files, the OP wants "fstream". The Pseudo-code would be:
1
2
3
4
5
6
7
8
9
10
std::string Output;

switch(choice)
{
     case 1:/*Load Text From File 1 to Output*/; break;
     case 2:/*Load Text From File 2 to Output*/; break;
     //Etc etc etc...
}

std::cout << Output;

The OP wants to include code. #include is what is needed:

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

using namespace std;

int main()
{
    ....
    if (choice == 1)
    {
        #include "MyChoice1File"
    }
    else if (choice == 2)
    {
        #include "MyChoice2File"
    }
    ....
}


That should work OK. AFAIK, the preprocessor will include your file exactly where you asked for it. The #include directive is not limited to header files.

BUUUUTTTTTT: It is awful! You want functions at the very least.
Topic archived. No new replies allowed.