cin、cout、>>、get()以及getline()

来源:互联网 发布:php 互换数组里面的值 编辑:程序博客网 时间:2024/05/01 11:20
上一篇博客明白了C和C++的字符串,那么这一篇来写输入输出流;

在头文件iostream中定义了cin,cout,cerr,clog 4个流对象,cin是输入流,cout,cerr,clog是输出流。

输出/cout

缓冲区:由于ostream类对cout对象处理的输出进行缓冲,所以输出不会立即发送到目标地址,而是在存储在缓冲区,直到缓冲区填满,程序将刷新缓冲区(flush),把内容发送出去,并清空缓冲区,以存储新的数据。当标准输出连接的是硬盘上的文件时,缓冲可以省略大量的时间;
屏幕输出时候,换行符发送到缓冲区后,将刷新缓冲区,另外,多数C++实现都会在输入即将发生时刷新缓冲区,如下:

cout<<"Enter a number: ";float num;cin>>num;


上述程序因为程序等待输出,刷新了缓冲区,屏幕立刻显示cout的消息;
如果程序不能再希望时刷新,可以使用强制刷新控制符:flush和endl(它们的区别就是endl多写入一个换行符);

格式化输出:

在头文件iomanip中,包含一些控制符,可以清晰方便地实现格式输出;
dec --- 置基数为10,后由十进制输出(系统默认形式)
hex --- 置基数为16,后由十六进制输出
oct --- 置基数为8,后由八进制输出
setfill(c) --- 设填充字符为c
setprecision(n) --- 设置实数的精度为n位
setw(n) --- 设域宽为n个字符
▲setbase(int n) : 将数字转换为 n 进制.
如 cout<<setbase(8)<<setw(5)<<255<<endl;
cout<<setbase(10)<<setw(5)<<255<<endl;
cout<<setbase(16)<<setw(5)<<255<<endl;
结果是:
(空格)(空格)377
(空格)(空格) 255
(空格)(空格)(空格) f f
▲ setprecision用法
使用setprecision(n)可控制输出流显示浮点数的数字个数。C++默认的流输出数值有效位是6。
如果setprecision(n)与setiosflags(ios::fixed)合用,可以控制小数点右边的数字个数。setiosflags(ios::fixed)是用定点方式表示实数。
如果与setiosflags(ios::scientific)合用, 可以控制指数表示法的小数位数。setiosflags(ios::scientific)是用指数方式表示实数。
setiosflags(ios::fixed) 固定的浮点显示
setiosflags(ios::scientific) 指数表示
setiosflags(ios::left) 左对齐
setiosflags(ios::right) 右对齐
setiosflags(ios::skipws) 忽略前导空白
setiosflags(ios::uppercase) 16进制数大写输出
setiosflags(ios::lowercase) 16进制小写输出
setiosflags(ios::showpoint) 强制显示小数点
setiosflags(ios::showpos) 强制显示符号
其中:setw设置域宽,使用一次就得设置一次,其他的函数,设置一次永久有效。
可以这样写:cout<<fixed<<right 这样就是定点计数,右对齐;

输入

关于输入,需要总结的是cin、>>、get、getline()这几个操作符或者说方法;
>>:抽取运算符,从流中读取数据,以空格结尾(空格、制表、换行),并将空格留在输入队列中,返回调用该运算符的对象的引用;
流状态:eofbit,如果到文件末尾返回1;failbit,读取文件失败返回1,badbit,位置错误返回1;具体调用可以:cin.eof();
cin>>input;流状态良好的情况下,返回true;
如果流状态位被设置,那么后面的输入或输出会关闭,直到位被清除:cin.clear();
get(),cin.get(char&)和ch=cin.get()均读取一个字符,即使是空白、制表符、换行符;

特征

Cin.get(ch)

Ch=cin.get()

传输方法

赋给参数ch

函数返回值赋给ch

返回值

指向istream对象的引用

字符编码(int值)

达到文件末尾的返回值

转换为false

EOF


cin.getline(char* str,int 20);读取整行,以\n为结尾,或者说读取\n并保存为\0;从键盘读取19个字符到字符数组str,因为最后一个是\0;
cin.get(char* str,int n);唯一不同就是它不再读取\n字符,在遇到它就结束运行,将\n留在输入队列中;不带参数的cin.get()函数可以读取下一字符,即使是换行符,因此可以用它来处理换行符;为读取下一行做准备;所以一般使用方法是cin.get(str,20).get();
cin.get(char*,int,char)和cin.getline(char*,int,char)的主要区别是,get()函数将换行符(分界符)留在输入流中,getline函数则抽取并丢弃输入流中的换行符;


下面是一些简单代码

一个简单的输入异常机制
#include<exception>int main(){    using namespace std;    cin.exceptions(ios_base::failbit);    cout << "Enter numbers: " << endl;    int sum = 0;    int value = 0;    try    {        while (cin >> value)            sum += value;    }    catch (ios_base::failure & bf)    {        cout << bf.what() << endl;        cout << "O! the horror!\n";    }    cout << "Last value entered= " << value << endl;    cout << "Sum= " << sum << endl;    return 0;}

处理输入错误的一个简单机制
#include<iostream>#include<cstdlib>int main(){    using namespace std;    int sum = 0;    int value = 0;    cout << "Enter your numbers: " << endl;    while (cin >> value)        sum += value;    cout << "Last value inputed: " << value << endl;    cout << "Sum= " << sum << endl;    if (cin.fail() && !cin.eof())  //failed because of mismatched input    {        cin.clear();        while (!isspace(cin.get()))            continue;    }    else      //else bail out    {        cout << "I cannot go on!\n";        exit(1);    }    //It can work now    cout << "Now enter a new number: ";    cin >> value;    cout << "The new number is: " << value;    return 0;

cin.get(char*,int,char)和cin.getline(char*,int,char)的实例;cin.get(...)将分界符丢弃在输入流中,cin.getline(...)则不然;

#include<iostream>const int Limit = 255;int main(){    using namespace std;    char input[Limit];    cout << "Enter a string for  getline() processing:\n";    cin.getline(input, Limit, '#');    cout << "Here is your input:\n";    cout << input << "\nDone with pase1\n";    char ch;    cin.get(ch);    cout << "The next input character is " << ch << endl;    if (ch != '\n')        cin.ignore(255, '\n');     //discard rest of line    cout << "Enter a string for get() processing:\n";    cin.get(input, Limit, '#');    cout << "Here is your input:\n";    cout << input << "\nDone with phase2" << endl;    cin.get(ch);    cout << "The next input character is: " << ch << endl;    return 0;}

检查是否读入了'#',然后决定下一步动作
#include<iostream>int main(){    using namespace std;    char ch;    while (cin.get(ch))    {        if (ch != '#')            cout << ch;        else        {            cin.putback(ch);            break;        }    }    if (!cin.eof())    {        cin.get(ch);        cout << endl << ch << " is the next input charater.\n";    }    else    {        cout << "End of the file reached.\n";        exit(0);    }    while (cin.peek() != '#')    {        cin.get(ch);        cout << ch;    }    if (!cin.eof())    {        cin.get(ch);        cout << endl << ch << " is the next character inputed.\n";    }    else        cout << "end of file reached.\n";    return 0;}

读取一行,处理下一行

#include<iostream>const int SIZE = 10;inline void eatline(){ while (std::cin.get() != '\n') continue; }int main(){    using namespace std;    char name[SIZE];    char title[SIZE];    cout << "Enter your name: ";    cin.get(name, SIZE);    if (cin.peek() != '\n')        cout << "Sorry,we only have enough room for " << name << endl;    eatline();    cout << "Dear " << name << ", enter your title:\n ";    cin.get(title, SIZE);    if (cin.peek() != '\n')        cout << "We were forced to truncate your title.\n";    eatline();    cout << " Name: " << name << endl;    cout << "Title: " << title << endl;    return 0;}



0 0