計算機概論實習 2007-03-09. 2 Stream Stream: sequence of bytes Input: from device (keyboard,...
-
date post
21-Dec-2015 -
Category
Documents
-
view
229 -
download
0
Transcript of 計算機概論實習 2007-03-09. 2 Stream Stream: sequence of bytes Input: from device (keyboard,...
計算機概論實習計算機概論實習2007-03-092007-03-09
2
StreamStream
Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer, etc.)
in c
scanf("%c", &ch); in c++
cin >> ch;
in c
printf("%c", ch); in c++
cout << ch;
byte stream
byte stream
Computer
3
iostream Library Header Filesiostream Library Header Files
iostream library Has header files with hundreds of I/O capabilities <iostream.h>
Standard input (cin) Standard output (cout) Unbuffered error (cerr) Buffered error (clog)
<iomanip.h> Formatted I/O with parameterized stream manipulat
ors <fstream.h>
File processing operations
4
Standard input (Standard input (cincin))
Format input cin >> grade Need to include iostream and std:cin
Using >> operator Normally skips whitespace (blanks, tabs, newlines)
Can change this Returns 0 when EOF encountered
Otherwise, returns reference to object State bits set if errors occur
Discussed in 12.7 and 12.8
5
Standard output (Standard output (coutcout))
Format input cout << grade Need to include iostream and std:cout
Using << operator
6
Exmaple CodeExmaple Code
#include <iostream>
using namespace std;
void main(){
int i;
cin >> i;
cout << i;
}
7
Multi-Input/OutputMulti-Input/Output
int main(){
int a, b;
cout << “Input two number: ”;
cin >> a >> b;
cout << “The inputs are ” << a << “ and ” << b;
return 0;
}
Input two number: 4 7
The inputs are 4 and 7space
8
Member Function: cin.get()Member Function: cin.get() get(charRef)
With character reference argument Gets only one character, stores in charRef
Returns reference to istream If EOF, returns -1
get(charArray, size) get(charArray, size, delimiter)
Reads until size-1 characters read, or delimiter encountered Default delimiter '\n' Delimiter stays in input stream
Can remove with cin.get() or cin.ignore() Makes array null-terminated
9
Member Function: cin.getline()Member Function: cin.getline()
getline(array, size) getline(array, size, delimiter)
Reads size-1 characters, or until delimiter found Default delimiter '\n'
Removes delimiter from input stream Puts null character at end of array
10
What Difference Among cin, cin.get(), and cWhat Difference Among cin, cin.get(), and cin.getline() (1/3)in.getline() (1/3)
int i;
cin >> i;
cout << “i = ” << i;
4 5 6 \n
4 5 6 \n
i = 456
i = 456
\n
skip due to >>
\n
11
What Difference Among cin, cin.get(), and cWhat Difference Among cin, cin.get(), and cin.getline() (2/3)in.getline() (2/3)
char ch[10];
cin.get(ch, 10);
cout << ch;
4 5 6 \n
\n 4 5 6 \n
ch[0] = ‘4’ch[1] = ‘5’ch[2] = ‘6’ch[3] = 0
ch[0] = 0
5 6 \n\n6 \n
Delimiter stays in input stream
Nothing is read
12
What Difference Among cin, get(), and getliWhat Difference Among cin, get(), and getline() (3/3)ne() (3/3)
char ch[10];
cin.getline(ch, 10);
cout << ch;
4 5 6 \n
\n 4 5 6 \n
ch[0] = ‘4’ch[1] = ‘5’ch[2] = ‘6’ch[3] = 0
ch[0] = 0
5 6 \n\n6 \n
4 5 6 \n
Removes delimiter from input stream
13
Throw Away DelimiterThrow Away Delimiter
If use cin.get(), the delimiter will stay in the stream. Using the following method to Throw it Away.
int main() {char buf[100];char trash;while(cin.get(buf,100)) { // Get chars until ‘\n’
cin.get(trash); // Throw away the terminatorcout << buf <<'\n'; // Add the ‘\n’ at the end
} return 0;}
Input : This is a test
Output: This is a test
14
Stream Error StatesStream Error States
Test state of stream using bits eofbit set when EOF encountered
Function eof returns true if eofbit set cin.eof()
failbit set when error occurs in stream Data not lost, error recoverable Function fail() returns true if set
15
Stream Error StatesStream Error States
badbit set when data lost Usually nonrecoverable Function bad()
goodbit set when badbit, failbit and eofbit off Function good()
16
Stream Error StatesStream Error States
Member functions rdstate()
Returns error state of stream Can test for goodbit, badbit, etc. Better to test using good(), bad()
clear() Default argument goodbit Sets stream to "good" state, so I/O can continue Can pass other values
cin.clear( ios::failbit ) Sets failbit Name "clear" seems strange, but correct
17
int main(){
int integerValue;
// display results of cin functions
cout << "Before a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good()
<< "\n\nExpects an integer, but enter a character: ";
cin >> integerValue; // enter character value
cout << endl;
18
// display results of cin functions after bad inputcout << "After a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()<< "\n cin.eof(): " << cin.eof() << "\n cin.fail(): " << cin.fail() << "\n cin.bad(): " << cin.bad() << "\n cin.good(): " << cin.good() << endl << endl;
cin.clear(); // clear stream// display results of cin functions after clearing cincout << "After cin.clear()"
<< "\ncin.fail(): " << cin.fail()<< "\ncin.good(): " << cin.good() << endl;
return 0;}
19
Before a bad input operation:cin.rdstate(): 0 cin.eof(): 0 cin.fail(): 0 cin.bad(): 0 cin.good(): 1
Expects an integer, but enter a character: c
After a bad input operation:cin.rdstate(): 2 cin.eof(): 0 cin.fail(): 1 cin.bad(): 0 cin.good(): 0
After cin.clear()cin.fail(): 0cin.good(): 1
Different error bit set leads to different value of rdstate()
20
Error Input Format – Simple ExampleError Input Format – Simple Example
int main () {
int a;
while (cin>>a){
cout<<"The input is:" <<a<<endl;
}
cout << "fail?" << cin.fail();
}
123The input is:123abcfail? 1
21
Error Input Format – Complex ExampleError Input Format – Complex Example
123The input is:123
abfail?1
ab1fail?1
123bThe input is:123fail?1
1
2
3
4
22
Explanation of Example - 1Explanation of Example - 1
If there are not any error input, then program can get value from cin stream.
while (cin>>a) 123
a=123
23
Explanation of Example - 2Explanation of Example - 2
When the input appears format error, the failbit set. In other words, the return value of cin.fail() is 1.
But, the cin stream still keep the input value. For example, when you input ab, it will be kept in the s
tream.
while (cin>>a)
a b
aba = -87361838cin.fail() = 1
24
Explanation of Example - 4Explanation of Example - 4
When you input 1ab, a will be 1 but the ab will be kept in the cin stream.
When you try to get from cin stream again, the failbit set.
while (cin>>a) a b
1ab
a=1cin.fail() = 0
a=-8193787cin.fail() = 1
First time
Second time
25
Error Input Format – Another ExampleError Input Format – Another Example
Reset cin state and clear the stream. Then to request user to re-input with correct format (ex. Integer).
26
Example ProgramExample Program
// in order to prevent user from inputting incorrect format, clear streamvoid clear2eol(){ cin.ignore(numeric_limits<streamsize>::max(), '\n'); }int main(){ int a; while (cout << "Enter a number: " && !(cin >> a)) { cin.clear(); // reset cin iostate as goodbit clear2eol(); // clear the stream cout << "Wrong input. "; } clear2eol();
return 0;}
Need include limits
Note that this code can not check the error such as “23abc”
27
Practice 1 (P1)Practice 1 (P1)
Try to write a program that request user to input the student’s information including name and score and output the information. Please check that if the input of score is correct. If the
input is not correct, then to request the user to re-input until the program gets a correct one.