首页 技术 正文
技术 2022年11月15日
0 收藏 967 点赞 4,234 浏览 1228 个字

zoj遇到c++如何判定输入流结尾的问题,一不小心就超时了

楼下的代码可以通过zoj

#include<iostream>
using namespace std;
int main(){
int a,b;
while(true){
cin>>a>>b;
if(cin.eof()){//换成fail(),或是good()也可以通过
break;
}
int sum=a+b;
cout<<sum<<endl;
}
return 0;
}这里也可以通过
#include<iostream>
using namespace std;
int main(){
    int a,b;
    while(cin>>a>>b){
    int sum=a+b;
    cout<<sum<<endl;
    }
    return 0;
楼下的代码无法通过
#include<iostream>
using namespace std;
int main(){
int a,b;
while(cin.eof()){//无法通过zoj
cin>>a>>b;int sum=a+b;
cout<<sum<<endl;
}
return 0;
}

话说到底是因为什么呢,oj的测试用例我没有猜到,在这里找到一些想法 http://stackoverflow.com/questions/13343991/c-why-cin-eof-read-last-char-twice

在这里我得到一些启发

http://blog.chinaunix.net/uid-27034868-id-3758629.html

这是一个读取文件的例子

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(){
char data;
ifstream infile;
infile.open("in.txt");
if(infile.fail()){
cout<<"fail to open"<<endl;
return 1;
}
while(1){
infile>>data;
if(infile.eof()){//注意这里 将循环结束的条件设置在读完一次数据后面,如果将判断条件放在while里面
break;
}
cout<<data;
} /*while(!infile.eof()){//这样的话 文件的最后一个字符将输出两次 比如in.txt="aaa" 那么标准输出将会是aaaa四个
明明使用了eof()判断了,为什么还是这样的呢 原因是这样的,因为eof()发现读到文件结束标志EOF时并不会立刻返回而是比较后知后觉(这段话摘自楼上给的链接的博客,话说我没有账号,不过觉得这种想法是错误的,根据单步调试的结果来看一旦infile接受了eof就会触发eofbit,也即
判断成功结束循环)
        infile>>data;
        cout<<data;
    }*/
infile.close();
cout<<endl;
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918