24小时热门版块排行榜    

CyRhmU.jpeg
查看: 484  |  回复: 3

sciencejoy

新虫 (著名写手)

[交流] C++读文件已有1人参与

C++读文件需要声明输入流变量,指明文件名。需要头文件fstream
CODE:
#include <cassert>
#include <iostream>
#include <fstream>

int main (int argc, char* argv[])
{
     double x[6], y[6];
     std::ifstream read_file("Output.dat");
     assert(read_file.is_open());
     for(int i=0;i<6;i++)
     {
         read_file >> x[i] >> y[i];
     }

     read_file.close();
     return 0;
}

以上的代码中,我们知道要读取的文件6行2列,但很多时候,我们并不知道文件有多长。如果文件有两列,但不知道有多少行,但肯定少于100行,不能用for循环,可以用while循环,
CODE:
#include <cassert>
#include <iostream>
#include <fstream>

int main (int argc, char* argv[])
{
     double x[100], y[100];
     std::ifstream read_file("Output.dat");
     assert(read_file.is_open());

     int i=0;
     while(!read_file.eof())
     {
          read_file >> x[i] >> y[i];
          i++;
     }

     read_file.close();
     return 0;
}

[ Last edited by sciencejoy on 2014-1-15 at 17:13 ]
回复此楼
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

icearchive

银虫 (初入文坛)


小木虫: 金币+0.5, 给个红包,谢谢回帖
for和while的功能是一样的,跟do{}while有点区别,你这个一样可以用for
2楼2014-01-15 17:02:44
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

sciencejoy

新虫 (著名写手)

引用回帖:
2楼: Originally posted by icearchive at 2014-01-15 17:02:44
for和while的功能是一样的,跟do{}while有点区别,你这个一样可以用for

说来看看
3楼2014-01-15 17:13:31
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

icearchive

银虫 (初入文坛)


小木虫: 金币+0.5, 给个红包,谢谢回帖
for (int i = 0; !read_file.eof(); i ++)
4楼2014-01-15 17:44:11
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 sciencejoy 的主题更新
普通表情 高级回复(可上传附件)
信息提示
请填处理意见