21xrx.com
2025-03-28 06:45:12 Friday
文章检索 我的文章 写文章
C++记事本源代码
2023-07-12 02:31:09 深夜i     133     0
C++ 记事本 源代码 编程 文本编辑器

C++记事本是一款非常实用的文本编辑器,它可以帮助我们轻松地创建、编辑和保存各种文本文件。下面是一个非常简单且易于理解的C++记事本源代码,它包含了许多常用的文本编辑功能。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
  bool isExit = false;
  ofstream outfile;
  string fileName;
  string text;
  while (!isExit) {
    int choice;
    cout << "请选择功能:\n";
    cout << "1.新建文件\t2.打开文件\t3.保存文件\t4.退出程序\n";
    cin >> choice;
    switch (choice) {
    case 1:
      cout << "请输入文件名:";
      cin >> fileName;
      outfile.open(fileName.c_str());
      if (outfile.is_open())
        cout << "文件创建成功!" << endl;
       else
        cout << "文件无法创建!" << endl;
      
      break;
    case 2:
      cout << "请输入文件名:";
      cin >> fileName;
      ifstream infile(fileName.c_str());
      if (infile.is_open()) {
        string line;
        while (getline(infile, line))
          cout << line << endl;
        
        infile.close();
      } else
        cout << "文件无法打开!" << endl;
      
      break;
    case 3:
      if (outfile.is_open())
        cout << "请输入文本内容:";
        cin >> text;
        outfile << text << endl;
       else
        cout << "请先打开文件!" << endl;
      
      break;
    case 4:
      isExit = true;
      outfile.close();
      cout << "程序已退出!" << endl;
      break;
    default:
      cout << "无效的输入,请重新输入!" << endl;
      break;
    }
  }
  return 0;
}

上述代码中,我们主要使用了`ofstream`和`ifstream`类,分别用于输出和读取文件。当用户选择新建文件时,我们可以通过`outfile.open`方法创建一个新的文件,并且可以检查文件是否成功创建。当用户选择打开文件时,我们可以通过`ifstream`读取文件内容,使用`getline`方法读取每一行,最后显示在控制台上。用户可以通过输入文件名和文本内容来保存编辑后的文件。

此外,我们还使用了`switch`语句来实现不同的功能选择,并且通过`while`循环来不断显示菜单,直到用户选择退出程序。

总的来说,这个C++记事本源代码非常简单易懂,但却包含了许多实用的文本编辑功能,可以帮助初学者更好地理解C++的文件操作。

  
  

评论区

请求出错了