文件流中的for是如何自增的?
我在看钱能的书第二版,遇到一个问题就是文件流操作中for()总是只有两个量,没有自增部分,请问如何实现自增,代码如下:
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream in( "a.in ");
ofstream out( "a.out ");
for(string str; getline(in,str); ) //没有自增的部分
out < <str < <endl;
}
//====================================================
还有一个求素数的例子也是没有自增部分,代码如下
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
vector <int> prime(10000,1);
for(int i=2; i <100; ++i)
if(prime[i])
for(int j=i; i*j <10000; ++j)
prime[i*j]=0;
ifstream in( "a.txt ");
for(int a; in> > a && a> 1 && a <10000; ) //没有自增部分
cout < <a < < " is " < <(prime[a] ? " " : "not ") < < "a prime.\n ";
return 0;
}
给入门级的我详细一些解释,不甚感激拉。
[解决办法]
for(string str; getline(in,str); )
其实你要理解for 的处理就明白了
for(赋值;条件判断;自增/减)
只要条件判断成立就再循环,只有条件判断是必须的, getline(in,str),当取完时 会返回0,这时for 循环就退出了
没有自增部分,是因为条件判断的地方就已经完成了需要的操作
就好像
for(i=0;++i <5;)一样
[解决办法]
yelling已经说的比较清楚了
你再看看关于“流”的东西
那你的代码来说吧(稍微改了下)
#include <fstream>
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream in( "a.txt ");
string temp;
if(!in) //无法打开文件
{
cout < < "Open file error\n ";
exit(1);
}
in> > temp;
cout < <temp;
cout < <endl;
in> > temp;
cout < <temp;
}
如果你写个a.txt的内容如下
aaa bbb ccc
那上面这段代码就会这样输出
aaa
bbb
这样明白了么?