⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 writingexceptions.cpp

📁 C++高级编程这本书所附的源代码
💻 CPP
字号:
#include <fstream>#include <iostream>#include <vector>#include <string>#include <stdexcept>#include <sstream>using namespace std;class FileError : public runtime_error{public:  FileError(const string& fileIn) : runtime_error(""), mFile(fileIn) {}  virtual ~FileError() throw() {}  virtual const char* what() const throw() { return mMsg.c_str(); }  string getFileName() { return mFile; }protected:  string mFile, mMsg;};class FileOpenError : public FileError{public:  FileOpenError(const string& fileNameIn);  virtual ~FileOpenError() throw() {}};FileOpenError::FileOpenError(const string& fileNameIn) : FileError(fileNameIn){  mMsg = "Unable to open " + fileNameIn;}class FileReadError : public FileError{public:  FileReadError(const string& fileNameIn, int lineNumIn);  virtual ~FileReadError() throw() {}  int getLineNum() { return mLineNum; }protected:  int mLineNum;};FileReadError::FileReadError(const string& fileNameIn, int lineNumIn) :  FileError(fileNameIn), mLineNum(lineNumIn){  ostringstream ostr;  ostr << "Error reading " << fileNameIn << " at line " << lineNumIn;  mMsg = ostr.str();}void readIntegerFile(const string& fileName, vector<int>& dest)  throw (FileOpenError, FileReadError) {  ifstream istr;  int temp;  char line[1024]; // assume no line is longer than 1024 characters  int lineNumber = 0;  istr.open(fileName.c_str());  if (istr.fail()) {    // We failed to open the file: throw an exception    throw FileOpenError(fileName);  }  while (!istr.eof()) {    // Read one line from the file    istr.getline(line, 1024);    lineNumber++;    // Create a string stream out of the line    istringstream lineStream(line);    // Read the integers one-by-one and add them to the vector    while (lineStream >> temp) {      dest.push_back(temp);    }    if (!lineStream.eof()) {      // Some other error. Close the file and throw an exception.      istr.close();      throw FileReadError(fileName, lineNumber);    }  }  istr.close();}int main(int argc, char** argv){  vector<int> myInts;  const string fileName = "IntegerFile.txt";  try {    readIntegerFile(fileName, myInts);  } catch (const FileError& e) {    cerr << e.what() << endl;    exit (1);  }  for (unsigned int i = 0; i < myInts.size(); i++) {    cout << myInts[i] << " ";  }  cout << endl;  return (0);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -