0%

标准输入输出流和标准错误流介绍

本篇笔记包含以下内容:

  • 标准错误流cerr
  • 标准输入流cin的部分方法
  • 标准输出流cout的部分方法

标准错误流cerr

标准错误流cerr用于向控制台输出错误信息

cerr与cout的区别

代码示例:

#include <iostream>
#include <math.h>
#include <string>
using namespace std;


void test1();

int main(int argc, const char * argv[]) {
    // insert code here...
    test1();
    
    return 0;
}

void test1()
{
    cout << "请输入姓名和年龄:";
    string name;
    int age;
    cin >> name >> age;
    if (age <= 0) {
        cerr << "\n年龄不能小于0!";
    }else{
        cout << name << " is " << age;
    }
}	

标准输入流cin

下面对cin的一些方法进行简要介绍,这些方法可以增强对输入操作的控制

get()

cin.get()接受一个输入字符(包括空白符,制表符,回车符),并返回该字符值,.

void test2()
{
    char tmp;
    cin.get(tmp);
    cout << "input: " << tmp << endl;
}

ignore()和getline()

cin.ignore(int n)的作用是忽略前n个输入的字符.

cin.getline()接输入的一行字符, 可以通过参数控制截取的字符数量.

void test3()
{
    char buf[20];
    cout << "input a text: \n";	//输入:123456789
    cin.ignore(5);					//忽略前5个字符
    cin.getline(buf, 3);			//截取两个字符
    cout << buf << endl;			//输出67
}

peek()

cin.peek()方法从输入流中指针指向的字符, 不修改指针, 而get()方法会使指针后移.

void test4()
{
    char p;
    cout<<"input text: \n";
    
    while (cin.peek() != '\n') {
        cout << (p=cin.get());
    }
    cout << endl;
    
}

read()和write()

read方法接受指定数目的字符到数组中(可读入空白符). write方法从数组中输出指定数目的字符, 若指定数目大于数组长度, 则输出整个数组.

void test5(){
    const int SIZE = 50;
    char buf[SIZE];
    cout << "input text : \n";
    cin.read(buf, 5);
    cout << "read方法读入的字符串长度是: " << cin.gcount();
    cout << "输入的文本是:\n";
    cout.write(buf, 3);
    cout << endl;
}	

标准输出流cout

下面介绍一些限制输出结果格式的方法

precision()

precision方法可以通过四舍五入保留指定的精度.

void test6()
{
    double result = 3.141592654;
    for (int i = 0; i <= 9; i++) {
        cout.precision(i);
        cout << result <<endl;
    }
}

输出结果为:	
3
3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265

C++中数据的最小有效长度为1, 所以上面传入0和1的结果是一样的.