When you are reading some data from a file, you can hard-code the file name via ''ifstream''. However, this is not the most convenient way. Every Linux/Unix system has intrinsic features named standard input(stdin), standard output(stdout), and pipe. As name suggests, stdin and stdout are the standard way for a program to communicate with environment or other programs. For further information, see http://en.wikipedia.org/wiki/Standard_streams.
#include <iostream> #include <string> using namespace std; ... ... while(1){ string input; getline( cin, input ); if( input[0] == '\0' ) break; .... .... }
Above code reads from stdin line by line. '\0'
is a special character that indicates a newline. Therefore, above code reads from stdin until it ends or it becomes a blank line. Now you can manipulate data line by line stored in input
with something like sscanf. Be aware
sscanf( char* pointer_to_src, FORMAT, pointers_to_variables )
should be fed with char*
in pointer_to_src
. Raw string variable input
will not work.
If your data file has certain fixed structure, then you can also do as:
for(int i=0; i < 100; i++ ){ int num, first, second; scanf( "%d %2x%2x", &num, &first, &second ); }
However, this is not as flexible as the one that uses getline
because, for example, it does not tell you when to stop reading. You can use it if you know the number of lines( 100 in the example above ) from stdin.
There is an easy way to feed data to your program stdin. This is the main reason we make use of stdin in our program.
./a.out < data_file
Your shell will interpret this command that the content of data_file
is going into stdin of a.out
. It now accepts a data file with any name!