码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 中的循环与分支以及简单的文件操作

时间:2018-06-22 17:47:52      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:关闭   cout   sts   code   getline   ice   lse   show   exit   

一 两种常用循环:
(1) for循环

for ( initial statement ; test_statement ; update_statement ){
statement list ;
}
(2) while 循环

                             while( statement ){
                                             statement_lists ;
                                             };

                             do {
                                    statement_lists ;
                                }while( test_statement );

(3)   基于范围的for循环  C++11特性

                                double prices [5] = { 12 , 27.2 , 20.24 , 89 , 3.28 };
                                for ( double x : prices )
                                                cout<< x << std::endl ;
                                //   这种方式无法修改数组的值

                                double prices [5] = { 12 , 27.2 , 20.24 , 89 , 3.28 };
                                for ( double &x : prices )
                                                x *= 0.8 ;
                                //   修改数组的值需要使用&

二 关于分支:
(1) if - else if - else
(2) test_statement ? var1 : var2
(3) switch - case
(4) 循环中的continue与break

三 简单的文件操作:
(1) 写入到文本文件中
#include <isotream>
#include <fstream>

                ofstream fout ;
                fout.open(text_dir);

                // 像使用cout一般对fout操作
                fout<< strings ;
                fout.setf(ios_base::showpoint);
                fout.precision(2);
                //  使用 fout.setf 可以修改输入到文件中的格式
                fout.close()
                // 关闭文件

(2)读取文本文件
#include <isotream>
#include <fstream>

                ifstream fin ;
                fin.open(text_dir);

                //检测是否已经打开了文件
                if( !fin.is_open() ){
                                exit(EXIT_FAILURE);
                                }
                fin.getline(array, size);
                //  如同对待cin一般对fin操作 

                fin.close()
                // 关闭文件

c++ 中的循环与分支以及简单的文件操作

标签:关闭   cout   sts   code   getline   ice   lse   show   exit   

原文地址:http://blog.51cto.com/13824643/2131873

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!