【c++】c++输入和输出的简单介绍

发布于:2025-09-06 ⋅ 阅读:(15) ⋅ 点赞:(0)

C++输⼊&输出

• 是InputOutputStream的缩写,是标准的输⼊、输出流库,定义了标准的输⼊、输出对象。

• std::cin是istream类的对象,它主要⾯向窄字符(narrowcharacters(oftypechar))的标准输⼊流。

• std::cout是ostream类的对象,它主要⾯向窄字符的标准输出流。

• std::endl是操作符,底层实现是⼀个函数,流插⼊输出时,相当于插⼊⼀个换⾏字符加刷新缓冲区。

• <<是流插⼊运算符,>>是流提取运算符。(C语⾔还⽤这两个运算符做位运算左移/右移)

• 使⽤C++输⼊输出更⽅便,不需要像printf/scanf输⼊输出时那样,需要⼿动指定格式,C++的输⼊输出可以⾃动识别变量类型(本质是通过函数重载实现的),其实最重要的是 C++的流能更好的⽀持⾃定义类型对象的输⼊输出。

• IO流涉及类和对象,运算符重载、继承等很多⾯向对象的知识。

• cout/cin/endl等都属于C++标准库,C++标准库都放在⼀个叫std(standard)的命名空间中,所以要通过命名空间的使⽤⽅式去⽤他们。

• ⼀般⽇常练习中我们可以using name space std,实际项⽬开发中不建议using name space std。

• 这⾥我们没有包含<stdio.h>,也可以使⽤printf和scanf,因为包含间接包含了<stdio.h>。vs系列编译器是这样的,其他编译器可能会报错。

#include<iostream>  
using namespace std; 
int main() 
{ 
	int a = 0; 
	double b = 0.1; 
	char c = 'x';
    cout << a << " " << b << " " << c << endl; 
    std::cout << a << " " << b << " " << c << std::endl; 
    scanf("%d%lf", &a, &b); 
    printf("%d %lf\n", a, b); 
    // 可以⾃动识别变量的类型  
    cin >> a; 
    cin >> b >> c; 
    cout << a << endl; 
    cout << b << " " << c << endl; 
    return 0; 
}
#include<iostream> 
using namespace std; 
int main() 
{ 
    // 在io需求⽐较⾼的地⽅,如部分⼤量输⼊的竞赛题中,加上以下3⾏代码  
    // 可以提⾼C++IO效率  
    ios_base::sync_with_stdio(false); 
    cin.tie(nullptr); 
    cout.tie(nullptr); 
    return 0; 
} 
#include<iostream>
using namespace std;
int main()
{
	int i = 100;
	double d = 1.1;

	//任何变量都转换成字符串插入流中
	//自动识别类型
	cout << i << '\n' << "\n";//'\n'和"\n"都行
	cout << "hello world" << endl;//endl也相当于换行符,但是会刷新缓冲区,而"\n"不会刷新缓冲区
	cout << i << " " << d;
	return 0;

}

运行结果
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到