Tuesday, August 9, 2022

PROGRAMMIMG

ảnh Long Hoang



 #include <iostream>

#include <fstream>

using namespace std;


int main() {

  // Create and open a text file

  ofstream MyFile("filename.txt");


  // Write to the file

  MyFile << "Files can be tricky, but it is fun enough!";


  // Close the file

  MyFile.close();

}




*****



// Create a text string, which is used to output the text file

string myText;


// Read from the text file

ifstream MyReadFile("filename.txt");


// Use a while loop together with the getline() function to read the file line by line

while (getline (MyReadFile, myText)) {

  // Output the text from the file

  cout << myText;

}


// Close the file

MyReadFile.close();



******



#include <iostream>

#include <fstream>

#include <string>

using namespace std;


int main () {

  // Create a text file

  ofstream MyWriteFile("filename.txt");


  // Write to the file

  MyWriteFile << "Files can be tricky, but it is fun enough!";

 

  // Close the file

  MyWriteFile.close();


  // Create a text string, which is used to output the text file

  string myText;


  // Read from the text file

  ifstream MyReadFile("filename.txt");


  // Use a while loop together with the getline() function to read the file line by line

  while (getline (MyReadFile, myText)) {

    // Output the text from the file

    cout << myText;

  }


  // Close the file

  MyReadFile.close();

}



*****



try {

  // Block of code to try

  throw exception; // Throw an exception when a problem arise

}

catch () {

  // Block of code to handle errors

}



*****



try {

  int age = 15;

  if (age >= 18) {

    cout << "Access granted - you are old enough.";

  } else {

    throw (age);

  }

}

catch (int myNum) {

  cout << "Access denied - You must be at least 18 years old.\n";

  cout << "Age is: " << myNum;

}


****



#include <iostream>

using namespace std;


int main() {

  try {

    int age = 15;

    if (age >= 18) {

      cout << "Access granted - you are old enough.";

    } else {

      throw (age);

    }

  }

  catch (int myNum) {

    cout << "Access denied - You must be at least 18 years old.\n";

    cout << "Age is: " << myNum;  

  }

  return 0;

}


Access denied - You must be at least 18 years old.
Age is: 15





No comments:

Post a Comment