This commit is contained in:
2025-10-01 19:49:29 +07:00
parent 19009082de
commit f00a12b32e
14 changed files with 218 additions and 72 deletions

View File

@@ -1,31 +1,50 @@
// Task 12 (Ubuntu): replace every char equal to the first char of its line with a space.
// Usage: ./task12 <input_file> → writes "<input_file>.out" and prints replacement count.
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <string> #include <string>
#include <sys/stat.h> #include <sys/stat.h>
#include <cerrno>
#include <cstdlib>
#include <climits>
// True if file exists (POSIX stat)
static bool file_exists(const std::string &path) { static bool file_exists(const std::string &path) {
struct stat st{}; struct stat st{};
return ::stat(path.c_str(), &st) == 0; return ::stat(path.c_str(), &st) == 0; // stat success => exists [web:59]
} }
// "<name>.out" by replacing last extension or appending if none
static std::string make_out_name(const std::string &in) { static std::string make_out_name(const std::string &in) {
std::size_t pos = in.find_last_of('.'); std::size_t pos = in.find_last_of('.');
if (pos == std::string::npos) return in + ".out"; if (pos == std::string::npos) return in + ".out";
return in.substr(0, pos) + ".out"; return in.substr(0, pos) + ".out";
} }
int main(int argc, char *argv[]) { static void print_usage(const char* prog) {
if (argc != 2) { std::cerr << "Usage: " << prog << " <input_file> <replace_count>\n"; // positional args [web:59]
std::cerr << "Usage: " << argv[0] << " <input_file>\n"; }
static bool parse_ll(const char* s, long long& out) {
if (!s || !*s) return false;
errno = 0;
char* end = nullptr;
long long v = std::strtoll(s, &end, 10); // use endptr and errno [web:59]
if (errno == ERANGE) return false;
if (end == s || *end != '\0') return false;
out = v;
return true;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
print_usage(argv[0]);
return -1; return -1;
} }
std::string in_path = argv[1]; std::string in_path = argv[1];
long long replace_limit = 0;
if (!parse_ll(argv[2], replace_limit) || replace_limit < 0) {
std::cerr << "Error: replace_count must be a non-negative integer.\n";
return -1;
}
if (!file_exists(in_path)) { if (!file_exists(in_path)) {
std::cerr << "Error: input file does not exist.\n"; std::cerr << "Error: input file does not exist.\n";
return -1; return -1;
@@ -44,18 +63,17 @@ int main(int argc, char *argv[]) {
return -1; return -1;
} }
long long replacements = 0; long long performed = 0;
std::string line; std::string line;
while (std::getline(in, line)) { while (performed < replace_limit && std::getline(in, line)) { // stop early when limit hit [web:59]
if (!line.empty()) { if (!line.empty()) {
char first = line.front(); char first = line.front();
for (char &c: line) { for (char &c: line) {
if (c == first) { if (c == first && c != ' ') {
if (c != ' ') { c = ' ';
c = ' '; ++performed;
++replacements; if (performed >= replace_limit) break; // cap reached [web:44]
} // count only real changes
} }
} }
} }
@@ -67,6 +85,23 @@ int main(int argc, char *argv[]) {
} }
} }
std::cout << replacements << std::endl; // If limit reached mid-file, copy the rest unchanged
return static_cast<int>(replacements); if (performed >= replace_limit) { // stream may be mid-line or between lines [web:59]
// Write remaining lines as-is
if (!in.eof()) {
// Flush any remaining part of current line already written; then dump rest
std::string rest;
while (std::getline(in, rest)) {
out << rest;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
}
}
std::cout << performed << std::endl; // print actual replacements up to limit [web:59]
return 0; // success [web:59]
} }

View File

@@ -1,28 +0,0 @@
## README.md
### Кратко
Работу выполнил студент группы АВТ-418 Куриленко Платон Семенович, вариант 12.
Программа построчно заменяет все символы, равные первому символу строки, на пробел; пишет результат в файл с суффиксом .out и выводит число замен в stdout.
### Сборка
```bash
./compile.sh
```
### Использование
```bash
./12_first_symbols_to_spaces <input_file>
```
Имя вывода: исходное имя с заменой последнего расширения на .out, либо добавлением .out (пример: a.txt → a.out; data → data.out).
### Коды возврата
- 0 при успехе; число замен также печатается в stdout.
- -1 при ошибке: сообщение об ошибке выводится в stderr.
### Быстрый тест
```bash
./run.sh
```
### Примечания
- Замены считаются только при реальной замене; если первый символ — пробел, такие позиции не увеличивают счётчик.

View File

@@ -1,25 +0,0 @@
1. Кратко
Работу выполнил студент группы АВТ-418 Куриленко Платон Семенович, вариант 12.
Программа построчно заменяет все символы, равные первому символу строки, на пробел; пишет результат в файл с суффиксом .out и выводит число замен в stdout.
2.Сборка
./compile.sh
3. Использование
./12_first_symbols_to_spaces <input_file>
Имя вывода: исходное имя с заменой последнего расширения на .out, либо добавлением .out (пример: a.txt → a.out; data → data.out).
4. Коды возврата
0 при успехе; число замен также печатается в stdout.
-1 при ошибке: сообщение об ошибке выводится в stderr.
5. Быстрый тест
./run.sh
6. Примечания
Замены считаются только при реальной замене; если первый символ — пробел, такие позиции не увеличивают счётчик.

View File

@@ -1 +1 @@
./12_first_symbols_to_spaces file.in ./12_first_symbols_to_spaces file.in 3

View File

@@ -0,0 +1 @@
g++ task18.cpp -o task18

View File

@@ -0,0 +1,11 @@
abcdef
abcdefg
abcdefghij
abc def
x
12
123
(three spaces)
abc
ab cs s dds
\tabcde\tf

View File

@@ -0,0 +1,67 @@
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
static bool file_exists(const std::string &path) {
struct stat st{};
return ::stat(path.c_str(), &st) == 0;
}
static std::string make_out_name(const std::string &in) {
std::size_t pos = in.find_last_of('.');
if (pos == std::string::npos) return in + ".out";
return in.substr(0, pos) + ".out";
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <input_file>\n";
return -1;
}
std::string in_path = argv[1];
if (!file_exists(in_path)) {
std::cerr << "Error: input file does not exist.\n";
return -1;
}
std::ifstream in(in_path);
if (!in) {
std::cerr << "Error: cannot open input file.\n";
return -1;
}
std::string out_path = make_out_name(in_path);
std::ofstream out(out_path);
if (!out) {
std::cerr << "Error: cannot create output file.\n";
return -1;
}
long long replacements = 0;
std::string line;
while (std::getline(in, line)) {
if (!line.empty()) {
for (std::size_t idx = 0; idx < line.size(); ++idx) {
std::size_t pos1 = idx + 1;
if (pos1 % 3 == 0) {
if (line[idx] != ' ') {
line[idx] = ' ';
++replacements;
}
}
}
}
out << line;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
std::cout << replacements << std::endl;
return static_cast<int>(replacements);
}

1
others/vlad`s/lab1/compile.sh Executable file
View File

@@ -0,0 +1 @@
g++ task11.cpp -o task11

View File

@@ -0,0 +1,13 @@
aabbcc
bookkeeper
Mississippi
x
aa
aba
aaa
baaa
aaab
abba
1222333
(four spaces)
--====

View File

@@ -0,0 +1,71 @@
// Task 11: In every pair of identical adjacent characters, replace the second with a space.
// Usage: ./task11 <input_file> -> writes "<name>.out" and prints replacements count.
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
static bool file_exists(const std::string &path) {
struct stat st{};
return ::stat(path.c_str(), &st) == 0;
}
static std::string make_out_name(const std::string &in) {
std::size_t pos = in.find_last_of('.');
if (pos == std::string::npos) return in + ".out";
return in.substr(0, pos) + ".out";
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <input_file>\n";
return -1;
}
std::string in_path = argv[1];
if (!file_exists(in_path)) {
std::cerr << "Error: input file does not exist.\n";
return -1;
}
std::ifstream in(in_path);
if (!in) {
std::cerr << "Error: cannot open input file.\n";
return -1;
}
std::string out_path = make_out_name(in_path);
std::ofstream out(out_path);
if (!out) {
std::cerr << "Error: cannot create output file.\n";
return -1;
}
long long replacements = 0;
std::string line;
while (std::getline(in, line)) {
if (!line.empty()) {
for (std::size_t i = 1; i < line.size(); ++i) {
if (line[i] == line[i - 1]) {
if (line[i] != ' ') {
line[i] = ' ';
++replacements;
}
// Move to next position; overlapping pairs like "aaa":
// i at 2 will compare line[2] with line[1] (now space) → no double count.
}
}
}
out << line;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
std::cout << replacements << std::endl;
return static_cast<int>(replacements);
}