您的位置:首页 > 编程语言 > C语言/C++

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

2018-03-30 20:10 836 查看

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;


可以来进行有关数值转换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐