c++ 控制台流和字符串流

来源:互联网 发布:java中级工程师就业班 编辑:程序博客网 时间:2024/05/22 06:42

前言

上一章节简单介绍c++中关于流的概念,这两章节将重点讲解如何使用,本章讲解控制台流和字符串流。

控制台输出流

输出流定义在头文件中,使用输出流最简单的方法就是 使用<<运算符。通过你<<可以输出c++基本类型。包括int、指针、double、字符

int ncount = 7;cout<<ncount<<endl;char *ch = "teststream";cout<<ch<<endl;//输出"teststream"cout<<*ch<<endl;//输出"t‘。
  • 输出流方法
    1、put、write是原始的输出方法,前者输出字符,后者输出字符数组或者字符串。
    2、 Flush
    向输出流写入数据时候,不一定立即将数据写入目标。大部分输出流都会进行缓冲,当满足以下条件时候,将进行刷新操作。
    a. 到达某个标记(endl)
    b. 流离开作用域
    c. 要求从对应的输入流输入数据的时候
    d. 流缓冲满 的时候。
    e.显示要求流刷新时。
    endl输出后,然后就是换行,flush则不换行。
  • 输出流操作算子
    流有一项独特的特性。c++流能识别操作流算子,操作流算子能够修改流行为的对象,而不是数据。
    这里写图片描述

控制台输入流

通过输入流可以简单读取数据。接收的类型输出所识别的类型一致。默认情况下,>>运算符根据空白符对输入值标志化,遇见空格符,后面的无法输入。如果用户输入hello there,输入的为hello。

char str[50];    int partsize;    cout<<"Name and Number of Guests"<<endl;    cin>>str>>partsize;    cout<<"Thank You"<<"."<<str<<endl;    cout<<partsize<<endl;    system("pause");

这里写图片描述
通过输入流可以读入多个值,而且可以根据需要混合和匹配类型。

  • 输入方法
    Get()方法允许从流中读入原始输入数据。只能读取char类型的。
    getline:从流中获取一行数据,用一行数据填充字符缓冲区,数据量最大到制定大小。指定大小包括\0字符。

字符串流stringstream

在程序中遇到格式转化怎么办?
比如从int转化为char类型,我们常用sprintf,使用此函数要保证1、必须确保证目标缓冲区有足够大空间以容纳转换完的字符串2、必须使用正确的格式化符

int n= 1000;char strs[20];sprintf_s(strs,"输入数值为:%d",n);//如果为下面就出错了sprintf_s(strs,"输入数值为:%f",n);cout<<strs<<endl;

定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另 外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。

    strstream sstream;    char* result = "10000";    int n = 0;    sstream<<result;    sstream>>n;//n 为1000    cout<<n;    system("pause");
#include<time.h>#include <sstream>//此处加载sstream头文件using namespace std;int main(){    stringstream sstream;    string result = "10000";//用string,在stream可以读取    int n = 0;    sstream<<result;    sstream>>n;    cout<<n;    system("pause");}

大量的字符串串联在一起,使用字符串流相率比反复调用string效率高.
如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;
你可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。例如,需要将各种数字值,如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝

void to_string1(string & result,const T& t){    ostringstream oss;//创建一个流,最好是全局变量,然后每次clear    oss<<t;//把值传递如流中    result=oss.str();//获取转换后的字符转并将其写入result}int main(){    stringstream sstream;    string result ;     to_string1(result,true);    to_string1(s2,123);//int到string    cout<<result;    getchar();}
#include <sstream>#include <iostream>int main(){    std::stringstream stream;    int first, second;    stream<< "456"; //插入字符串    stream >> first; //转换成int    std::cout << first << std::endl;    stream.clear(); //在进行多次转换前,必须清除stream    stream << true; //插入bool值    stream >> second; //提取出int    std::cout << second << std::endl;} 
0 0
原创粉丝点击