[C++复习]10|managing console I/O operations

[note 1]

character by character
[1] get

char a;
cin.get(a);
a=cin.get;

these 2 prototypes can be used to fetch a character including the blank space, tab and newline character.
[2] put

cout.put('x');
cout.put(a);

[note 2]

line-oriented input/output functions
[1] getline
(can read white space)

char name[20];
cin.getline(name,20);

[2] write
display an entire line.
Form:

cout.write(line,size);

[example 1]

#include<iostream>
#include<string>
using namespace std;

int main()
{
    char * string1="C++ ";
    char * string2="Programming";
    int m=strlen(string1);
    int n=strlen(string2);
    
    for(int i=1;i<n;i++)
    {
        cout.write(string2,i);
        cout << "\n";
    }
    for(int i=n;i>0;i--)
    {
        cout.write(string2,i);
        cout << "\n";
    }
    
    //contatenating strings
    cout.write(string1,m).write(string2,n);
    
    cout << "\n";
    
    //crossing the boundary
    cout.write(string1,10);
    
    return 0;
}


output:

P
Pr
Pro
Prog
Progr
Progra
Program
Programm
Programmi
Programmin
Programming
Programmin
Programmi
Programm
Program
Progra
Progr
Prog
Pro
Pr
P
C++ Programming
C++ ProgrProgram

[note 3]

formatted console I/O operations
[1] width

cout.width(w);
  • W is the field width
  • the ouput will be printed ina field of w characters wide at the right end of the field.
  • After printing one item, it will revert back to the default.

[2] precision

cout.precision(d);
  • d is the number of digits to the right of the decimal point.
  • remain effective until it is reset.
  • the output is rounded to the nearest cent.
  • trailing zeros are truncated.

[3] fill

cout.fill(ch);

[4] setf()

cout.setf(arg1,arg2);
  • arg1-formatting flags
  • arg2-bit field

[5]

扫描二维码关注公众号,回复: 8519616 查看本文章
cout.setf(ios::showpoint);  //display trailing zeros
cout.setf(ios::showpos);   //show + sign

[note 4]

the following function defines a manipulator called unit that displays “inches”:

ostream & unit(ostream&output)
{
	output<<"inches";
	return output;
}
发布了51 篇原创文章 · 获赞 5 · 访问量 4202

猜你喜欢

转载自blog.csdn.net/qq_43519498/article/details/92982525