函数c ++之间的异常处理

时间:2017-01-12 20:24:36

标签: c++ exception-handling stringstream

我正在C ++课程中学习基本的OOP。我们的一个任务是从文件中读取行,通过将字符串转换为字符串流的函数(parseLine())运行它们,从该parseLine中抛出异常,捕获readFile函数中的异常并写入抛出的行控制台的例外情况。不抛出异常的行应该添加到struct数组中。

问题:投掷没有被抛出或没有被抓住。

我花了几个小时玩格式化试图找出为什么我的try catch语句不起作用。我希望我能提出更具体的问题,但我相信对于看到我的代码的更有经验的程序员来说,答案是显而易见的

注意:格式化风格由班级规定。

/**********************************************************************
* struct: Record
* fileName
* user
* time
***********************************************************************/
struct Record
{
   string file;
   string user;
   long time;
};

/**********************************************************************
* function: parseLine
* parse line into struct
***********************************************************************/
void parseLine(const string & line, Record & buffer) throw (string)
{
   assert(line.length() > 0);

   stringstream ss;
   ss.str(line);

   // stream string to struct
   ss >> buffer.file;
   if (ss.fail())
   {
      ss.clear();
      throw string(line);
   }
   ss >> buffer.user;
   if (ss.fail())
   {
      ss.clear();
      throw string(line);
   }

   ss >> buffer.time;
   if (ss.fail() || buffer.time < 1,000,000,000 || buffer.time > 10,000,000,000)
   {
      ss.clear();
      throw string(line);
   }
}

/**********************************************************************
* function: readFile
* read from the file name provided by the user
***********************************************************************/
int readFile(const string & fileName, Record record[])
{
   // declare fstream variable
   ifstream fin(fileName.c_str());

   // error check
   if (fin.fail())
   {
      cout << "ERROR: Unable to read file "
           << fileName
           << endl;
      return 0;        
   }

   // loop through file and store it
   Record buffer;
   string line;
   int size = 0;
   while (getline(fin, line) && size < 500)
   {
      try
      {
         parseLine(line, buffer);
         record[size] = buffer;
      }
      catch (string text)
      {
         cout << "Error parsing line: "
              << text
              << endl;
      }
      size++;
   }

   // close the file
   fin.close();
   return size;
}

问题1 正在阅读的文件故意包含错误(空行,意外地点的内容等),似乎ss.fail()没有被触发,怎么会发生?

问题2 我的try / catch块是否正确写入?

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您的整数文字不应包含逗号。

逗号实际上是一个C ++运算符。