소스코드
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename, content;
cout << "Welcome to the Basic Text Editor!" << endl;
cout << "Enter the filename to open or create: ";
cin >> filename;
ifstream inFile(filename);
if (inFile) {
// File exists, read its content
string line;
while (getline(inFile, line)) {
content += line + '\n';
}
inFile.close();
} else {
cout << "File does not exist. Creating a new one." << endl;
}
char choice;
do {
cout << "1. View/Edit Content\n2. Save and Quit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case '1':
cout << "Current content:\n" << content << endl;
cout << "Enter new content (Ctrl+D to finish):\n";
cin.ignore();
content = "";
while (cin) {
string line;
getline(cin, line);
content += line + '\n';
}
break;
case '2':
ofstream outFile(filename);
outFile << content;
outFile.close();
cout << "File saved. Exiting." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != '2');
return 0;
}
프로그램 동작 방식
- 열거나 생성하려는 파일 이름을 입력합니다.
- 파일이 이미 존재하면 해당 파일의 내용을 읽어옵니다. 존재하지 않으면 새 파일을 생성합니다.
- 파일의 내용을 보거나 편집하거나, 저장하고 종료할지 선택할 수 있습니다.
- 내용을 보거나 편집하려고 할 때, 현재 내용을 표시하고 편집할 수 있게 해줍니다.
- 저장하고 종료하려고 할 때, 변경 내용을 파일에 저장하고 프로그램을 종료합니다.
결과
Welcome to the Basic Text Editor!
Enter the filename to open or create: mydocument.txt
File does not exist. Creating a new one.
1. View/Edit Content
2. Save and Quit
Enter your choice: 1
Current content:
Enter new content (Ctrl+D to finish):
This is a sample text.
You can edit it here.
Press Ctrl+D (or Ctrl+Z on Windows) to save and exit.
1. View/Edit Content
2. Save and Quit
Enter your choice: 2
File saved. Exiting.
'Programming language > C++' 카테고리의 다른 글
[C++] 환율 계산 프로그램 (0) | 2023.10.06 |
---|---|
[C++] 행맨(Hang man) 구현하기 (0) | 2023.10.06 |
[C++] To-Do Program 개발하기 (1) | 2023.10.06 |
[C++] 업다운 게임 구현하기 (숫자맞추기) (0) | 2023.10.06 |
[C++] 계산기 만들기 (0) | 2023.10.06 |