1.5 输入输出初步

来源:互联网 发布:mac book屏保aerial 编辑:程序博客网 时间:2024/05/17 07:07

     C++的输入/输出功能由输入/输出流(iostream)库提供。输入/输出流库是C++中一个面向对象的类层次结构,也是标准库的一部分。

     终端输入,也被称为标准输入(standard input),与预定义的iostream对象cin绑定在一起。直接向终端输出,也被称为标准输出,预定义的对象cout绑定在一起。第三个预定义的iostream对象cerr被称为标准错误,也与终端绑定。cerr通常用来产生给程序用户的警告或错误信息。

     任何要想使用iostream库的程序必须包含相关的系统头文件:

                   #include <iostream>

     输出操作符<<用来将一个值导向到标准输出cout或者标准错误cerr上。例如:

 

              int v1, v2;

              // ...

              cout << "The sum of v1 + v2 = ";

              cout << v1 + v2;

              cout << '/n';

 

     输入操作符>>用来从标准输入读入一个值。

 

             string file_name;

             // ...

             cout << "Please enter input and output file names: ";

             cin >> file_name;

 

     连续出现的输入操作符也可以连接起来例如

 

             string ifile, ofile;

             // ...

             cout << "Please enter input and output file names: ";

             cin >> ifile >> ofile;

 

     怎样读入未知个数的输入值呢?在l.2 节结束的时候我们已经做过,请看下面的代码序列:

 

            string word;

            while ( cin >> word )

            // ...

 

     在while 循环中每次迭代都从标准输入读入一个字符串直到所有的串都读进来当到达文件结束处end-of-file 时条件( cin >> word )为假,第20 章将解释这是如何发生的下面是使用这段代码序列的一个例子

 

 

           #include <iostream>

           #include <string>

 

           int main()

          {

                 string word;

                 while ( cin >> word )

                        cout >> "word read is: " >> word >> '/n';

                        cout >> "ok: no more words to read: bye!/n";

 

                 return 0;

           }

原创粉丝点击