← ppnm

Exercise C++ input/output

Tasks:

  1. Command-line

    Read a set of numbers from the command-line argument in the form (we follow the Unix option convension),

    ./main -n 1 -n 2 -n 3 -n 4 -n 5 > Out.txt 
    and print these numbers together with their sines and cosines (in a table form) to the standard output. Something like
    int main (int argc, char* argv[]) {
    	std::vector<double> numbers;
    	for(int i=0;i<argc;++i){
    		std::string arg=argv[i];
    		if(arg=="-n" && i+1<argc)
    			numbers.push_back(std::stod(argv[i+1]));
    	}
    for(auto n: numbers)
    	std::cout << n <<" "<< std::sin(n) <<" "<< std::cos(n) <<std::endl;
    exit(EXIT_SUCCESS);
    }
    
    The program can get the numbers from the command-line directly,
    ./main -n 1 -n 2 -n 3 -n 4 -n 5 > out.txt
    
    or, alternatively, if the line of numbers is too long, one can write the numbers into a file and then "cat" the file into the command line,
    echo "-n 1 -n 2 -n 3 -n 4 -n 5" > inputfile
    ./main $(cat inputfile) > out.txt
    
    The length of the command line is limited though, so the size of the file should not exceed your command line limit (probably about 2 megabytes).

  2. Standard input stream

    Read a sequence of numbers from the standard input and print these numbers together with their sines and cosines (in a table form) to the standard output. Something like

    double x;
    while( std::cin >> x ){
    	std::cout << x <<" "<< std::sin(x) <<" "<< std::cos(x) << std::endl;
    	}
    
    The program can be run as
    echo 1 2 3 4 5 | ./main > out.txt 
    or
    echo 1 2 3 4 5 > input.txt
    ./main < input.txt > out.txt
    
    or
    echo 1 2 3 4 5 > input.txt
    cat input.txt | ./main > out.txt
    
  3. File streams

    Read a set of numbers separated by whitespaces from "inputfile" and write them together with their sines and cosines (in a table form) to "outputfile". The program must read the names of the "inputfile" and "outputfile" from the command-line,

    ./main --input my_input_file.txt --output my_output_file.txt
    
    Something like
    int main (int argc, char *argv[]) {
    	std::string infile="", outfile="";
    	for(int i=0;i<argc;i++){
    		std::string arg=argv[i];
    		if(arg=="--input" && i+1 < argc) infile=argv[i+1];
    		if(arg=="--output" && i+1 < argc) outfile=argv[i+1];
    	}
    std::ifstream myinput(infile);
    std::ofstream myoutput(outfile);
    double x;
    if( myinput.is_open() && myoutput.is_open() ){
    	while( myinput >> x ){
    		myoutput << x <<" "<<std::sin(x)<<" "<<std::cos(x)<<std::endl;
    		}
    	}
    else{
    	std::cerr << "Error opening files: " << infile << outfile << std::endl;
    	return EXIT_FAILURE;
        }
    myinput.close();
    myoutput.close();
    exit(EXIT_SUCCESS);
    }