728x90
Input Stream
scanf has the input problem cause it doesn't do the boundary check, so does cin. For more security:
char name[4];
cin >> setw(4) >> name;
0
|
1
|
2
|
3
|
H
|
W
|
I
|
\0
|
Stream States
Old (C):
if (fgets(line, 10, stdin) != NULL)
{
// ...
}
New:
cin >> line;
if (!cin.eof())
{
// ...
}
Istream states
- namespace : ios_base
- bit flag : goodbit, eofbit, failbit, badbit
- method : good(), eof(), fail(), bad()
example
int number;
cin >> number;
input
|
eofbit
|
failbit
|
456abc
|
unset
|
unset
|
456
|
console - unset / file - set
|
unset
|
abc
|
unset
|
set
|
eof
|
set
|
set
|
Discarding Input
clear( )
makes good state
cin.clear();
ignore( )
stops when reaches the eof or discards the specified number of characters
cin.ignore(); // discard 1 character
cin.ignore(10); // discard 10 characters
cin.ignore(10, '\n'); // discard 10 characters, stop when discard the newline char
cin.ignore(LLONG_MAX, '\n'); // discard LLONG_MAX, stop when discard the newline char
get( )
retrieves all characters before the newline character. Newline character remains in the input stream.
get(name, 100);
// get 99 chars or chars before the newline char
// put the chars in the array 'name'
get(name, 100, '#');
// get 99 chars or chars before the '#' char
// put the chars in the array 'name'
getline( )
retrieves all characters before the newline character. Newline character is discarded in the input stream.
getline(name, 100);
getline(name, 100, '#');
728x90
'College Study > C++ (ENG)' 카테고리의 다른 글
[C++] File I/O (ENG) (0) | 2022.01.02 |
---|---|
[C++] File I/O (ENG) (0) | 2022.01.02 |
[C++] String (ENG) (0) | 2021.12.05 |
[C++] New Concepts (ENG) (0) | 2021.12.05 |
[C++] Output (ENG) (0) | 2021.12.05 |
댓글