Simple UNIX commands I/O techniques in C++ Solutions to Lab#0 problems Solutions to Lab#1 problems 1
Unix Environment Input Output 3
Change Directory (cd) ◦ cd [directory name] ◦ Use [Tab] button for auto-completion List Content (ls) ◦ ls (list current directory) ◦ ls –all (include hidden files/folders) Remove Directory Entries (rm) ◦ rm [file/folder name] C++ Compile (g++) ◦ g++ -Wall myprogram.cpp –o myprogram ◦ -o option is used to specify the output file name. This option is optional. By default the output file name is “a.out”. -Wall is used to show all warnings. 4
Edit File in VIM (vim) ◦ vim [file name] Running C++ Program ◦./myprogram (or./a.out) ◦./myprogram [output file] (input/output redirection) Checking for Difference (diff) ◦ diff [file name] [file name] ◦ Difference in a single space or an extra line will be noted Manual (man) ◦ man [command name] ◦ When you are not sure what the command does, or what parameter it expects 5
Command Mode: (to get into command mode, press ESC key) 1. dd or :d → Delete the current line 2. :q! → Exit without saving changes 3. :wq or ZZ → Save and Exit 4. /[pattern] → Search for the pattern ◦ n → Search next in the same direction ◦ N → Search next in the opposite direction See “Editor” in CS1020 Online web page: ◦ 6
Unix Environment Input Output 7
use istream cin Types of Input: (from Lab 0 Problem 1) o Type 1: Number of Operations is specified o Type 2: Read until Terminating Special Character/String o Type 3: Read until End of File 8
int numOps; cin >> numOps; for (int i=0; i<numOps; i++) { // Read Other Inputs } 9 int numOps; cin >> numOps; while(numOps--) { // Read Other Inputs } Method 2 (shorter ): Method 1: Why the second method works?
Steps: 1. Initialize a variable to store the input 2. Read the First Input 3. Loop until Terminating Special Character/String encountered 4. Read into tempInput again 10 string tempInput; cin >> tempInput; while (tempInput != TERMINATING_STRING) { // Read Other Input (if exist) cin >> tempInput // Step 4 }
Steps: 1. Initialize the variable to store the input 2. Loop until End of File 11 while (cin >> tempInput) { // Read Other Input }
Combines two or more different input types into a single program ◦ e.g.: Type 3 Input on the Outside, Type 1 Input on the Inside. 12 int numOps; while (cin >> numOps) { for (int i=0; i<numOps; i++) { // Read Other Inputs }
Unix Environment Input Output 13
With Extra Line at the End Without Extra Line at the End 14 cout << "Output String Here" << endl; cout << "Output String Here“; cout << "Output String Here\n";
Matrix Type, End Space Matrix Type, End Not Space 15 for (int i=0; i<numLine; i++) { for (int j=0; j<numOut; j++) { cout << output << " "; } cout << endl; } for (int i=0; i<numLine; i++) { cout << output; for (int j=1; j<numOut-1; j++) { cout << output << “ “; } cout << output << endl; }
END OF FILE