C++ 基本输入输出以及字符串的介绍

本文介绍了C++中基本的输入输出操作,包括cin和cout的使用,以及endl与 的区别。此外还探讨了字符串的输入输出方法,如使用getline进行整行读取,并通过字符串流实现类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++的基本输入和输出

1.最常规的输入和输出

cin >>
cout <<

这俩的头文件是

endl 来表示换行,但这还有其他作用:

The endl manipulator produces a newline character, exactly as the insertion of ‘\n’ does; but it also has an additional behavior: the stream’s buffer (if any) is flushed, which means that the output is requested to be physically written to the device, if it wasn’t already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only when flushing the stream would be a feature and ‘\n’ when it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some devices it may produce a delay.

它会刷新输出缓冲区,这就意味着这输出需要被物理写入到设备。但这种缓冲区只针对完全缓冲流,而cout则不是完全缓冲流。用endl来代替\n是个好习惯。

但执行刷新操作是有代价的,对设备带来一些延迟。

2.对字符串的输入输出

对字符串,可以使用字符数组,但这是很麻烦的。
C++在中提供了字符串类型,可以直接定义。
使用getline(cin,string),这种来输入进string的变量,这种输入方式是作为一行来输入的,可以有相关空格。

如果使用 cin >> a,这样也可以的,但以空格作为结束,意味着无法输入空格。

字符串可以进行相关拼接操作,直接用 + 就能很好的解决,操作代码如下:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{

    string a,b;

    cin >> a;
    cin >> b;

    a=a+' '+b;

    cout << a << endl;  

    return 0;
}

3.字符串流

在中有stringstram()函数,可以将字符串类型转换为其他类型。

string mystr ("1204");
int myint;
stringstream(mystr) >> myint;

可以来进行有关数值转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值