为什么我的ifstream中有一个无限循环? 我学习C++。下面是我的简单代码,但我在下一行代码中遇到了一个问题: while(is >> p) vp.push_back(p); // TODO: here I have a problem...
在指定的行中,我接收无限循环。为什么会发生?我希望得到“eof”(即!is)并退出一个周期为什么我的ifstream中有一个无限循环? 我学习C++。下面是我的简单代码,但我在下一行代码中遇到了一个问题: while(is >> p) vp.push_back(p); // TODO: here I have a problem...,c++,C++,在指定的行中,我接收无限循环。为什么会发生?我希望得到“eof”(即!is)并退出一个周期 /* main.cpp © AB, 10/06/2013 Chapter 10, Exercise 1. */ //------------------------------------------------------------------------------------------------- #include <exception> #include <iostream
/*
main.cpp
© AB, 10/06/2013
Chapter 10, Exercise 1.
*/
//-------------------------------------------------------------------------------------------------
#include <exception>
#include <iostream>
#include <string>
#include <vector>
#include<fstream>
using namespace std;
// Some structure...
struct Point{
int x, y;
Point(int xx, int yy): x(xx), y(yy){}
Point(): x(0), y(0) {}
};
ostream& operator << (ostream& os, const Point& p){
os << p.x << ',' << p.y;
return os;
}
istream& operator >> (istream& is, Point& p){
char ch;
int x,y;
if((cin >> x >> ch >> y) && ch == ',') p = Point(x,y);
return is;
}
//=================================================================================================
int main()
try{
vector<Point> vp;
Point p;
while(cin){
// Get some data...
cout << "x,y: ";
cin >> p;
if(cin) vp.push_back(p);
}
// print
for(int i = 0; i < vp.size(); ++i) cout << vp[i] << ' ';
cin.clear();
string s;
// save to file
cout << endl << "Output file name: ";
if(!(cin >> s)) throw runtime_error("Invalid output file name.");
{ // create output stream
ofstream os(s.c_str());
if(!os) throw runtime_error("Can't open file: " + s);
for(int i = 0; i < vp.size(); ++i) os << vp[i] << ' ';
} // here ofstream erased
cout << "Read back..." << endl;
vp.clear();
ifstream is(s.c_str()); // create input stream
if(!is) throw runtime_error("Can't open file: " + s);
while(is >> p) vp.push_back(p); // TODO: here I have a problem...
for(int i = 0; i < vp.size(); ++i) cout << vp[i] << ' '; // print
}
catch(exception& e){
cerr << e.what() << endl;
return 1;
}
catch(...){
cerr << "Unknown exception." << endl;
return 2;
}
/*
main.cpp
©AB,10/06/2013
第10章,练习1。
*/
//-------------------------------------------------------------------------------------------------
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
//一些结构。。。
结构点{
int x,y;
点(intxx,intyy):x(xx),y(yy){
点():x(0),y(0){}
};
ostream&算子x>>ch>>y)和&ch==',')p=点(x,y);
回报是;
}
//=================================================================================================
int main()
试一试{
向量vp;
p点;
while(cin){
//获取一些数据。。。
cout>p;
如果(cin)副总裁推回(p);
}
//印刷品
对于(int i=0;i操作符>(istream&is,Point&p)
中,您使用的是cin
而不是is
您总是会得到一个无限循环,因为在运行循环之前,
is
是正常的,循环不会改变is
,因为在操作符>(istream&is,Point&p)
中,您使用的是cin
而不是is
您总是会得到一个无限循环,因为在运行循环之前,
is
是正常的,并且循环不会改变is
,因为在操作符>>(istream&is,Point&p)
你用cin
而不是is
@DyP这应该是答案。@DyP,谢谢你!我是一头瞎驴……:))因为在你的操作符>(istream&is,Point&p)
中你用cin
而不是is
@DyP这应该是答案。@DyP,谢谢你!我是一头瞎驴……)