第一章 快速入门 初窥输入输出

来源:互联网 发布:王心凌不火了 知乎 编辑:程序博客网 时间:2024/06/05 02:58

C++本身并没有定义输入输出语句,输入输出的功能是由标准库所提供。iostream库的基础是两类,分别是istream和ostream,分别表示输入输出流,流是指从io设备上读入或读出的序列。(流随时间顺序生成或消耗)


1、标准输入输出对象:

标准库定义了四个io对象:

1、cin 标准输入。

2、cout 标准输出。

3、cerr 标准错误。

4、clog 标准错误。

2、完成程序:

包含输入输出后的程序:


#include <iostream>//尖括号中的是标准库中的头文件,双引号是自己定义的头文件。


using namespace::std;//命名空间的作用:使用命名空间可以避免由于无意中使用了与库中所定义的名字相同而引起的冲突


int main(int argc,constchar * argv[])

{

cout<<"enter two numbers:"<<endl;//该句使用了两次输出操作符“<<”,每个输出操作符都要有两个操作对象,左操作数必须是ostream对象,右操作数是要输出的值。              //输出操作返回的值是输出流本身。注意前面所说的流的概念,所以可以将输出操作链接在一起。

int v1,v2;

cin>>v1>>v2;

cout<<"the sum of the two number:"<<v1+v2<<endl;

   return0;

}


enter two numbers:

1 2

the sum of the two number:3







习题解答:

1、编写一个程序,在标准输出打印“hello ,world”

#include <iostream>


int main()

{

std::cout <<"Hello, World!\n";

    return 0;

}


2、我们的程序利用内置的加法操作符来产生两个数的和编写程序,使用乘法操作符产生两个数的积。

#include <iostream>


using namespace::std;


int main()

{

int a,b;

cout<<"please enter the two number:"<<endl;

cin>>a>>b;

std::cout <<"the product of the two number is:"<<a*b<<endl;

   return0;

}


3、我们的程序使用了一条较长的输入语句,重写程序,使用单独语句打印操作数。

#include <iostream>


using namespace::std;


int main()

{

int a,b;

cout<<"please enter the two number:"<<endl;

cin>>a;

cin>>b;

std::cout <<"the product of the two number is:"<<a*b<<endl;

   return0;

}


4、解释下面的程序:

  std:cout<<"the sum of"<<v1;

          <<"and"<<v2;

          <<"is"<<v1+v2

          <<std:endl;

这段代码合法吗?为什么,如不,又为什么?


答:此代码不合法,分号是一条语句的结束,所以在前一句用分号时,下一句如果没有输出函数而只有操作符这会产生错误。



原创粉丝点击