iostream
library is
the cin
statement
(accessed via std::cin or cin >> variablename;
cin >> var1 >> var2 >> var3;(these can be of different types, but be sure to prompt the user clearly as to the order in which the data should be entered)
For example, suppose we have the code fragment
int Age; char Initial; float Income; cout << "Please enter your age, "; cout << "your middle initial, and your annual income, " << endl; cout << "e.g. 47 J 127,302.51" << endl; cin >> Age; cin >> Initial; cin >> Income;This will work correctly as long as there is some whitespace (spaces, tabs, newlines, etc) between each pair of values, and as long as the user hits enter after the final value.
cin.get()
// my variable location char mycharvar; // get the next character of data cin.get(mycharvar);
int x, y, z; cout << "Please enter three integers" << endl; cin >> x >> y >> z;If the user types in
3 7 21
but doesn't hit
return afterward the system will just sit there
int i; char c; float f; cout << "Please enter a character, an integer,"; cout << " and a floating point number" << endl; cin >> c >> i >> f;
From the command line in Unix (i.e. when you are working in a terminal or dtterm window, or using ssh) you can use a file of data to provide input to a program instead of retyping the data each time.
This is handy if you have test cases you want to retry every time
you alter the source code. Put the test cases in a file, and use
the <
symbol to direct the file data into your program:
csciun1.mala.bc.ca< myprogram < mydatafile(Assuming your executable file is named
myprogram
and your test data
is in file mydatafile
)
Note that when doing this the program doesn't take any input from the keyboard,
it gets it all from the data file, so your data file must contain all the
appropriate user responses in the correct order.
Also, the output is still printed to the monitor.
Files for storing output
Similarly, you can redirect the output from a program so that it is stored in a file instead of printed on the screen.
To do so, use the >
symbol:
csciun1.mala.bc.ca< myprogram > resultsfileIf you wanted to use one file for input and store the results in another file, you can combine the two commands, e.g.
csciun1.mala.bc.ca< myprogram < mydatafile > resultsfileUsing programs to provide input for programs
Finally, if you want to directly use the output from one program as the input to another, you can use a pipe symbol | to connect the two:
csciun1.mala.bc.ca< generatorprogram | userprogram