c++ - 文件结束无限while循环

标签 c++ while-loop eof

我正在编写这个程序,用于从文件中读取和计算本金和利息,并将表格打印到输出文件。一切正常,除了我不明白为什么我被困在 main 的 while 循环中。它正确地打印了我所有的数据,但它一直在等待另一个值并且不会退出。谁能给我一些启发?

int main()
{
  ifstream inData;
  ofstream outData;
  float principle=0;
  int years;
  float rate;

  inData.open("inputdata.txt");
  if (!inData){
   cout<<"Error opening file."<<endl;
   return 1;}

  outData.open("outputdata.txt");
  if (!outData){
   cout<<"Error opening file."<<endl;
   return 1;}

  getData(inData, principle, years, rate);

  while(!inData.eof(){
    printTable(outData, principle, years, rate);

    principle=0;
    getData(inData, principle, years, rate);
  }

  return 0;
}

void getData (ifstream& inData, float& principle, int& years, float& rate)
{
 char temp;
 int temp2=0;

 inData.get(temp);

 while(temp!=' '){
    if(isdigit(temp)){
        temp2=temp-'0';
        principle=(10*principle)+temp2;}

    inData.get(temp);
 }

 inData>>years>>rate;
}

最佳答案

读取完最后一条记录后,它会最后一次调用getData()。这将读取 temp,并且会失败,因为它位于文件末尾。然后它进入 while 循环。 temp 永远不会等于空格,因此它永远不会退出该循环。如果文件没有以空格结尾,您也会被卡住。

您需要在 getData() while 循环中检查 eof

关于c++ - 文件结束无限while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408179/

相关文章:

c++ - 原始内置类型初始化

c++ - 使用 long 的一般规则

c++ - 添加到整数对 vector 和字符串 vector 的元素在函数返回时被清除

Java - 马尔可夫链文本生成器 - 解析文本文件

C 初学者 : Does scanf "receive" the EOF marker from standard input?

c - scanf()如何返回EOF?

c++ - C++ 读取文件某个位置的字节

PHP 循环查询,第一行

C - 使用 fscanf 从文件中读取 '-1'

vb.net - 如何在 while 循环中限制 CPU 使用率