2. 输入输出
与C语言对比
C语言输入输出:
#include<stdio.h>
int main()
{
int a;
char b;
scanf("%d%c",&a,&b);
printf("a=%d,b=%c",a,b);
return 0;
}
C++输入输出
使用cout标准输出(控制台)和标准输入设备(键盘)时,必须使用头文件以及std标准命名空间,endl相当于/n;
#include<iostream>
using namespace std;
int main()
{
int a;
char b;
cin>>a>>ch; //cin输入流对象
cout<<"a="<<a<<"ch="<<ch<<endl;//cout输出流对象
}
//cin输入流对象,键盘
//cout输出流对象,屏幕
//>>提取符
//<<插入符
//endl=>'\n';换行符
//错误使用方法
cin>>a,ch;
cout<<a,ch;
输入字符串
cin函数是遇到’空格’ ‘TAB’ '回车’就结束取值
cin.getline(字符串名称,字符串字符个数,结束字符)可以接受空格等
可以简写cin.getline(字符串名称,字符串字符个数)
#include<iostream>
using namespace std;
int main()
{
const int n=128;
char str[n];
cin>>str;//输入:hello world
cout<<str<<endl;//输出:hello
//cin.getline(字符串名称,字符串字符个数,结束字符)
cin.getline(str,n);//输入:hello world
cout<<str<<end;//输出:hello world
cin.getline(str,n,'#');//输入:hello world h#fhx
cout<<str<<endl;//输出:hello word h
return 0;
}