Чтобы принимать полную строку после команды -a, включая пробелы, необходимо собрать все аргументы в функцию main и объединить их в одну строку. Вот как можно изменить код:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <stdexcept>
#include <unistd.h>
#include <pwd.h>
std::string getFilePath() {
const char* homeDir = getenv("HOME");
if (!homeDir) {
struct passwd* pw = getpwuid(getuid());
homeDir = pw->pw_dir;
}
return std::string(homeDir) + "/bullet/dat.md";
}
void addLine(const std::string &line) {
std::ofstream file(getFilePath(), std::ios_base::app);
if (!file) {
throw std::runtime_error("Error opening file for writing.");
}
file << "- [ ] " << line << "\n";
}
void listLines(int start = 0, int end = -1) {
std::ifstream file(getFilePath());
if (!file) {
throw std::runtime_error("Error opening file for reading.");
}
std::string line;
std::vector<std::string> lines;
while (std::getline(file, line)) {
lines.push_back(line);
}
if (lines.empty()) {
std::cout << "All done\n";
return;
}
if (end == -1) {
end = lines.size();
}
for (int i = start; i < end && i < lines.size(); ++i) {
std::cout << i + 1 << " ⊷ " << lines[i].substr(5) << "\n";
}
}
void toggleLine(int lineNumber) {
std::ifstream file(getFilePath());
if (!file) {
throw std::runtime_error("Error opening file for reading.");
}
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line)) {
lines.push_back(line);
}
if (lineNumber < 1 || lineNumber > lines.size()) {
throw std::out_of_range("Line number out of range.");
}
if (lines[lineNumber - 1].substr(0, 5) == "- [ ] ") {
lines[lineNumber - 1].replace(0, 5, "- [x] ");
} else {
lines[lineNumber - 1].replace(0, 5, "- [ ] ");
}
std::ofstream outFile(getFilePath());
if (!outFile) {
throw std::runtime_error("Error opening file for writing.");
}
for (const auto &l : lines) {
outFile << l << "\n";
}
}
void deleteLine(int lineNumber) {
std::ifstream file(getFilePath());
if (!file) {
throw std::runtime_error("Error opening file for reading.");
}
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line)) {
lines.push_back(line);
}
if (lineNumber < 1 || lineNumber > lines.size()) {
throw std::out_of_range("Line number out of range.");
}
lines.erase(lines.begin() + lineNumber - 1);
std::ofstream outFile(getFilePath());
if (!outFile) {
throw std::runtime_error("Error opening file for writing.");
}
for (const auto &l : lines) {
outFile << l << "\n";
}
}
int main(int argc, char* argv[]) {
try {
if (argc < 2) {
std::cerr << "No command provided.\n";
return 1;
}
std::string command = argv[1];
if (command == "-a") {
if (argc < 3) {
std::cerr << "Missing argument for -a.\n";
return 1;
}
std::string lineToAdd;
for (int i = 2; i < argc; ++i) {
lineToAdd += argv[i];
if (i < argc - 1) {
lineToAdd += " "; // Add space between words
}
}
addLine(lineToAdd);
} else if (command == "-l") {
if (argc == 3) {
int num = std::stoi(argv[2]);
listLines(num - 1); // Convert to zero-based index
} else if (argc == 4) {
int num1 = std::stoi(argv[2]);
int num2 = std::stoi(argv[3]);
listLines(num1 - 1, num2); // Convert to zero-based index
} else {
listLines(); // List all
}
} else if (command == "-x") {
if (argc < 3) {
std::cerr << "Missing argument for -x.\n";
return 1;
}
int lineNum = std::stoi(argv[2]);
toggleLine(lineNum);
} else if (command == "-r") {
if (argc < 3) {
std::cerr << "Missing argument for -r.\n";
return 1;
}
int lineNum = std::stoi(argv[2]);
deleteLine(lineNum);
} else {
std::cerr << "Unknown command: " << command << "\n";
return 1;
}
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}
Изменения:
- Обработка аргументов для
-a: После -a программа теперь собирает всю строку с помощью цикла, начиная со второго аргумента (argv[2]) и заканчивая последним. Если есть больше одного аргумента, они объединяются в одну строку с пробелами между ними.
- Формирование строки: Проверьте, чтобы каждая пара слов была соединена пробелом. Это позволяет пользователю вводить фразы с пробелами.
Теперь, когда вы запускаете программу с командой -a, она корректно добавляет полную строку, даже если она содержит пробелы. Например:
./your_program -a "This is a test line"
Эта команда добавит строку - [ ] This is a test line в файл.