• *Wellcome Guest This Forum is created to help each other. Join us in our journey.

    * Guest Earn Piont Every Post, like, comment,and etc.

Managing the Console with the iostream Classes in C++

C

Chrysanthus Forcha

Guest
In computing, the console is the computer keyboard and the computer monitor. In the past, output was sent directly to the monitor screen and not to a window displayed on the monitor. For the ordinary computer user, applications today do not use the monitor explicitly. These applications use windows displayed on the monitor. However, the computer programmer still needs to use the monitor screen. Though the programmer still needs to use the monitor screen, the operating system does not allow him to do that. The operating system provides a window that simulates the monitor screen. In the Windows Operating System, this window is called the Command Prompt. In the Linux Operating System and its variants, this window is called the terminal.

It is expected that the reader already knows how to use the Command Prompt or the Terminal. This article explains how to read characters and strings from the keyboard and send characters and strings to the terminal (or command prompt). Every C++ programmer needs to know in this article.

In order to have input from the keyboard and output to the terminal, the program has to begin with:

#include <iostream>
using namespace std;
Article Content

Narrow Stream Objects of the Standard iostream


The iostream class, the standard objects, cout, cin, cerr, and clog, have been instantiated and already in the standard library. The programmer just uses them without instantiating them again.

cout


The following statement in the main() function sends the text, “This is output.” to the terminal:

cout << "This is output.";

cout is an output iostream object in the standard library, already instantiated. << is the insertion operator, which sent the bytes, “This is output.” to the output stream object, cout. When the statement is executed, the text appears on the screen.

With the above statement, the re-displayed command prompt appears on the right of the output phrase. It does not go to the next line. “endl” at the end of the following statement will force whatever is printed by the screen to the next line:

cout << "This is output." << endl;

“endl” is a predefined variable. Screen content can also be forced to the next line with:

cout << "This is output." << '\n';

With the use of ‘\n’, all the lines of text may still not appear on the screen immediately. “endl” flushes the complete line of text to the screen.

Note: a string sent to cout is in double quotes, while a character sent is in single quotes. A series of strings and chars can be sent in one statement, each preceded by << . All that will appear in one line at the output if ‘\n’ is not in the series.

cin


cin is the standard iostream input object, already instantiated, and available in the standard library. Consider the following code segment in the main() function:

char txt[50];
cout << "Enter a word and press Enter:" <> txt;
cout << txt << endl;

The first statement declares an empty array of 50 characters. The second statement instructs the user to type in a word on the next screen line and press the Enter key. Note the use of "endl" that forces the user to enter text in the next line of the screen. As the user types text, the entered text is echoed to the screen while it goes into the cin object. After pressing Enter, the third statement in the code segment is executed. This third statement sends the entered text to the variable, txt. The text entered should not be longer than 50 characters in this case. Note the use of the extraction operator, >>. The last statement displays the entered text on the screen.

cin can take more than one word from the keyboard, separated by spaces. These words will have to be extracted into different variables. The following code segment illustrates this:

char txt[20];
int it;
float ft;
cout << "Enter 3 values and press Enter:" <> txt >> it >> ft;
cout << txt << ' ' << it << ' ' << ft << endl;

Note the statement:

cin >> txt >> it >> ft;

The first word is extracted to txt, the next to it, and the last to ft. If the input was,

one 25 3.6

then the output by the code segment would be,

one 25 3.6
cerr


The following program has an error:

#include
using namespace std;

int main()
{

in myInt;

return 0;
}

The first statement in main() is not correct. If the name of the file having the code is “temp.cc” and the resulting executable file is to be called “temp”, then the following g++ command will send the compiler error message to the file, “error.txt”:

g++ -o temp temp.cc 2>error.txt

If the file “error.txt” does not exist, it would be created. Note the portion “2>error.txt” of the g++ command.

The screen is the standard output destination, and it is also the standard error destination. If “2>error.txt” is omitted from the g++ command, then the compiler error message would be sent to the standard error destination, which is still the screen (monitor).

The stream object that represents the standard output destination is cout. The stream object that represents the standard error destination is cerr. A program runtime error can be sent to the screen as follows:

cerr << "The error message!" << '\n';
clog


An application takes different inputs at different times. All the inputs can be re-displayed on the screen. All the inputs can be saved in a file. This is logging. The standard logging destination is the screen. The standard logging stream object is a clog. The following code will re-display the input text to the screen:

char txt[50];
cout<<"Enter text and press Enter:"<>txt;
clog<<txt<<endl;

If the input text is "input_text", then clog would re-display "input_text" to the screen.

In practice, logging is usually redirected to a file. The following program illustrates this:

#include
using namespace std;

int main()
{

freopen( "log.txt", "w", stdout);

cout << "input_text" << endl;
}

Note the use of the function, freopen(), and its arguments. Its first argument is the name of the log file. If the file does not exist, it would be created. Its second argument is "w" for "write". Its third argument is stdout for standard-output. The second statement in the main() function uses cout to send the logging text to the file. Note: The actual input code has not been shown in this program.

Obtaining Characters and Strings from the Keyboard


While the user is typing input, the characters are sent to the input stream buffer and displayed on the screen. When the user presses the Enter key, all the characters are in the buffer; also, the cursor goes to the beginning of the next line below, at the screen. The program then continues to the next program statement, after the input reading statement.

The cin object has methods, which this section is concerned with.

Reading the First Character


get(char_type& c):
The following code segment shows how to read the first character, from the input stream buffer:

char ch;
cout << "Input text:" << endl;
cin.get(ch);
cout << ch << endl;

The first statement declares a character without assignment. The second statement tells the user to input a character. When the user types in character and presses the Enter key, the third statement copies the character from the input stream buffer into the variable, ch.

Even if the user typed in more than one character, the first character would be taken by the code segment.

get():
get() without argument, returns the decimal ASCII code. Consider the following code segment:

cout << "Input text:" << endl;
cout << cin.get() << endl;

If the input is "asdfg", then 97 would be returned, which is the decimal ASCII code for 'a'.

get(char_type* s, streamsize n)


After the user inputs a phrase and presses the Enter key, a number of characters beginning from the first, can be extracted from the cin stream buffer. The following code can be used:

char str[10];
cout << "Input text:" << endl;
cin.get(str, 10);
cout << str << endl;

If the input is "great people," then the output will be "great peo", of 9 characters and not 10. The string NUL character (\0) takes the tenth position in the get argument. So, to have 9 characters in str, its storage size has to be at least 10, and the get() argument has to be 11. If the entire input line is desired, then the string storage number has to be at least the number of characters typed, plus 1. So, if 12 characters are typed for the entire line, then the number should be 13 for the string (str) storage size and 13 for the get() argument. Note that one space is counted as one character.

get(char_type* s, streamsize n, char_type delim)
It is possible to extract a sub-string, delimited on the right, by the first occurrence of a particular character, or by the sub-string’s streamsize, which ever comes first. If the input text to the following code is “great people”, then “great” would be extracted:

char str[30];
cout << "Input text:" << endl;
cin.get(str, 6, 'o');
cout << str << endl;

The sixth position from the beginning is the space character, and it delimits the extracted substring exclusively. The sixth position comes first before the only character, 'o'. Note that the storage size for str can be as high as possible.

If the input text to the following code is “great people”, then “gr” would be extracted:

char str[30];
cout << "Input text:" << endl;
cin.get(str, 10, 'e');
cout << str << endl;

The first occurrence of 'e', comes first before the tenth position.

Getting all the Characters of a Line


After pressing the Enter key, all the characters typed into the line, can be gotten as shown in the following code:

cout << "Input text:" << endl;
while (1) {
char ch = (char)cin.get();
cout << ch;
if (ch == '\n')
break;
}

The casting with (char), converts each decimal number into the corresponding ASCII character.

peek()


The get() member functions do not only read the next character; they remove it from the stream buffer. However, the peek() member function simple reads the next character (beginning from the first) without removing it from the buffer. In the following code, each character is first read with the peek() function before being removed, by the get() function. All that happens after the user presses the Enter key:

cout << "Input text:" << endl;
while (1) {
char ch = (char)cin.peek();
cout << ch;
cin.get();
if (ch == '\n')
break;
}

If the next characters were not removed by get(), peek() would only be reading the first character, and the loop will iterate indefinitely.

Displaying and Deleting Characters before pressing Enter


Notice that with the cin object, the Enter key has to be pressed before there will be action. Well, it is possible for characters to be displayed while being typed and erased before pressing the Enter key. However, that means interfacing with the operating system. Operating systems differ. So this means different coding for different operating systems. So this topic deserves a whole different tutorial – see later.

Sending Characters and Strings to the Monitor


The cout object is an output stream object, already instantiated and present in the C++ standard library. cout is the main object used in sending characters and strings to the monitor. This is done with the insertion operator, << . With the cin object, the text is obtained line-by-line. With the cout object, the text is added onto the same line until ‘\n’ or endl is encountered.

Expressions that result in scalars can be arguments for the insertion operator. The operator converts the scalar into text and places the text in the cout object stream. When text is sent to the cout object, it normally appears on the screen (monitor). However, occasionally, it may not appear immediately. To forced text onto the screen, insert the special value, “endl,” just after inserting the text. This will cause the text to be flushed to the screen, and a newline will be added. Note: ‘\n’ simply adds a newline but does not flush text to the screen.

The following program shows how to print the values of int, float, and ordinary text, onto the screen:

#include
using namespace std;

int main()
{

int it = 5;
float ft = 63.5;
cout << "The " << it << " items cost $" << ft << " US." << endl;

return 0;
}

The output is:

The 5 items cost $63.5 US.

The following program shows how the string of an object instantiated from a class is printed:

#include
using namespace std;

struct St {
char str[11] = "some words";
} obj;

int main()
{

cout << obj.str << '\n';

return 0;
}

The output is "some words".

Arguments for a C++ Program


Program execution begins from the main() function. The main() function actually has two optional parameters. The syntax of the main() function with the optional parameters, is:

int main (int argc, char *argv[argc])
{


return 0;
}

Assume that the name of the executable C++ file is “temp”. Assume that the arguments that the program needs from its environment (operating system), typed by the user, is,

articles 3 book pen "big house"

There are 5 arguments here: “articles”, “3”, “book”, “pen”, and “big house”

Each is text. A numbered argument to a program is text. In other words, each argument is a string. “big house” is in quotes because it is a phrase. The terminal command to run this program would be:

./temp articles 3 book pen "big house"

Assuming that the file temp is in the home directory. Note that spaces and not commas separate the arguments.

Now, in the main() function syntax, argc is the number of arguments for the program, plus 1. In this case, there are 5 arguments for the program. So, argc is 6. In the syntax, argv[argc] is an array of pointers to strings. The first value for this array at argv[0] is given by the compiler. It is a pointer to the name of the program file. The rest of the values are pointers to the program arguments in the user’s order typed in. The size of this array is argc. In this case the size is 1 + 5 = 6.

Assume that at compilation, the following program is named temp:

#include
using namespace std;

int main(int argc, char** argv)
{


cout << argv[0] << ", " << argv[1] << ", " << argv[2] << ", " << argv[3] << ", " << argv[4] << ", " << argv[5] << endl;

return 0;
}

Note here, that the array "char *argv[argc]", has been declared as "char** argv".

If this program is run with the terminal command,

./temp articles 3 book pen "big house"

then the output would be:

./temp, articles, 3, book, pen, big house

Note that the directory path has been included with the name of the executable file.

Also, note that in the running of the program (calling of the program), the value for argc has not been sent.

Conclusion


The iostream class has four important objects that are cout, cin, cerr, and clog. cin is an input object, while the rest are output objects. While a program is running, input to the program is different from when the program is to start running. When a program starts running, input to the program is joined with the command to run the program, separated by spaces.

Credit to linux
 

Latest threads

Top