C++文件读取末尾 eof()

       相信大家都有用过c++的文件读写流,在读写文件时,利用eof()来判断是否已经达到文件末尾,如下:

ifstream inf("test.txt");
		if ( !inf.is_open() )
		{
			cout <<"打开文件错误!" <>shape;
				inf >>answer;
				inf >>right_or_wrong;
				
				CPolygon *p;
				if ( shape == "正方形" ) p = (CPolygon *)(new CSquare(shape,answer,right_or_wrong));
				else if( shape == "长方形" ) p = (CPolygon *)(new CRectangle(shape,answer,right_or_wrong));
				else if ( shape == "月牙形" ) p = (CPolygon *)(new CCrescentShaped(shape,answer,right_or_wrong)) ;
				else if( shape == "三角形" )  p = (CPolygon *)(new CTriangle(shape,answer,right_or_wrong));
				else if( shape == "梯形" )  p = (CPolygon *)(new CTrapezoidal(shape,answer,right_or_wrong));
				else if( shape == "圆形" )  p = (CPolygon *)(new CRound(shape,answer,right_or_wrong));
				else  p = (CPolygon *)(new CStar(shape,answer,right_or_wrong));
				m_fromfile.push_back(p);
			}
		}
		inf.close();
       此时,我惊奇的发现在读取时,文件最后一个数据重复读取了一次,十分不解。在网上搜了一番,原来是在读取文件时,并没有管是否读取成功了,当在读到文件最后一个数据时,在去读取,实际上读取时失败的,而之前保存在shape等中的数据未发生变化,故又构造了一个对象,这就是看到的最后一个数据重复一次输出。

最简单的解决方法就是在读取之后判断是否读取成功了,可以在

                               inf >>right_or_wrong;
				CPolygon *p;
之间加上一条判断语句,判断是否读取成功。若失败,则跳出循环,反之,则继续执行。

				if(!inf)
				   break;
      这样程序就能正常执行了。

你可能感兴趣的:(c++,string,c,c/c++)