You are here:

C++/C++ : Reading commands from a txt 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.
Again thank you

The short answer is no.

The slightly longer answer is yes, but you have implement interpreting the commands from your text file in your program.

If you stop and think about this it makes sense. Assuming you have grasped how you (usually) build an executable program from C++ source code that is, which as a newbie at C++ you might not have yet. So I'll run through the process quickly now.

You write your C++ code in one or usually more than one text files. These are compiled by the C++ compiler. The output from the compiler is called an object file (that's a different use of object than in object-oriented) which generally contains, among other data, native machine code instructions for the processor the machine is using, or, if performing what is known as a cross-compilation, machine code for some other machine you are targeting your program to run on. Each source file compiled by the compiler typically produces one object file.

You then link these object files together, usually with additional pre-built libraries of object code to create the executable.
These stages in building a program are shown below (view it using a fixed-pitch font such as Courier, otherwise it will not display correctly):

<source files> ---> [compiler] ---> <object files>
         <other libraries> ---> [linker] ---> <executable>

When you execute the program you are executing native machine instructions, _not_ C++. You do not need the compiler after all the code has been compiled, nor do you require (much) of a runtime support system, as you do with environments like Java or .NET.

I say not much because you may require one or more shared runtime libraries (such as a MS Windows DLLs) on any machine that executes your program. It may in fact depend on how you choose to build you program - often you can choose between including all such runtime code in the executable or use libraries that are shared (DLLs).

Using shared libraries can save space because the common code in the shared library is shared by all programs using it, rather than being included in each program that uses the code. However it does mean you may have to ship addition files (the shared library files) with your program if you distribute it (or even just run it on another machine).

So to sum up: the only thing that understands C++ is the C++ compiler, and it forms no part of your program (unless your program is a C++ compiler of course <g>). In fact the object code and libraries linked to form your executable could have been compiled using different languages: maybe some were compiled using C or FORTRAN.

Thus your code has no knowledge of C++ or other language or command syntax unless you choose to give it that knowledge by writing code to make it understand (or of course making use of existing code someone else wrote - such as a library).

Knowing this you can simplify the syntax of your command file - after all the simpler it is the easier it will be to write code to understand the commands and execute them.

Another other option of course is to make your command file full blown C++ and compile it and link it with your stack code to create new executables. This may not be what you wish though, unless you are just trying to test your code or some such. In which case such commands would form the basis of unit tests for your code.

I suppose you could get your program to read the commands from the file, add additional code to make it buildable, write it to a source file file, execute the compiler and linker to build an executable from this created source file and then execute the resultant program. The only standard library way to execute one program from another is to use the system function:

   #include <cstdlib>

   // ...

   system(<comandline string>);

where <comandline string> is a placeholder for a C-style string (null character terminated array of char) that is the command line you wish to execute. The system function executes a command processor (such as the MS Windows cmd.exe) to execute the command line you pass it. No useful information is returned to the calling program (so it would be best to redirect standard and error output to files on the command line). The calling program waits until the command line finishes execution before continuing.

If you are implementing a stack just to see how to do so or because it is a course assignment or similar then fair enough.

However, if you are implementing a stack because you require one, and you have a fairly ISO C++ standard implementation of C++ (such as most modern compilers, released since around 1998 when the ISO C++ standard was published) then you can probably save yourself a lot of bother as the standard C++ library comes with a stack container adapter class template.

It is a container adapter because it adapts (i.e. uses) some other container type (vector, list, deque) for use as a stack. It is a class template because it is a generic type - a new class is created from the template for each stack of T required - where T is the type of the objects held by the stack:

   #include <stack>

   // ...

   // stack of int objects.
   // Uses the std::deque default as underlying container type
   std::stack<int>   st;

   // Use push operation to push values onto stack

   // Use top operation to access top value on stack
   int lastValueOnStack( );

   // Use pop to remove top item from stack

   int secondValueOnStack( );


   int firstValueOnStack( );

Disclaimer: The above code has not been tested, or even compiled. It is intended only to give an idea of how to use the std::stack class template. It may contain typos, errors, omissions etc. (and if so then I appologise!).

If you wish to make use of the C++ standard library then I suggest you obtain a decent reference such as "The C++ Standard Library A Tutorial and Reference" by Nicolai M. Josuttis. There are some online resources, e.g. and

Hope this is of some use.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2017 All rights reserved.

[an error occurred while processing this directive]