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

一 两种常用循环:
(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);
                //      这个部分可以直接写为 ofstream fout(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);
                //      这个部分可以直接写为 ifstream fin(text_dir) ;

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

                fin.close()
                // 关闭文件

转载于:https://blog.51cto.com/13824643/2131873

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值