You are here:

C++/Reading commands from text file


Hello and thank you very much for taking the time to read my question. I am implementing a simple data structure in c++ (a stack). The problem is that I want my program to read the commands from a text file. For example, if I want to push an item to the stack, I want to write in a text file (input.txt): push(item); and read my command from there. I have tried everything as far as reading from a file is concerned (using fstream) but I can only read the string. (It outputs: "push(item);" instead of executing it as a command). Is there a way this can be done? I am a total noob   in C++ and maybe the answer is simple but I can't find it anywhere.
Thanks again

Hello Chrysanthe, thank you for the question.

Unfortunately, there is no way to translate your custom string into an executable command. I think the easiest way to do this would be to implement a class that would be responsible for analyzing the string you read in from file and calling the appropriate methods. Here is an example

// In some class
void Class::TranslateString(const std::string &command)
if(command == "push(item)")
else if(command == "pop(item)")

That would be fairly easy, however, any time you changed the names of the specific commands you would have to update your source code. I wish I could give a more flexible answer, but custom file scripting always involves predetermined, hardcoded strings.

I hope this answer was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2017 All rights reserved.