Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Java программирование > Общие вопросы по Java, Java SE, Kotlin
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 24.03.2023, 19:27   #1
faktor
Пользователь
 
Регистрация: 14.02.2023
Сообщений: 10
По умолчанию Помогите пожалуйста переделать код C/C++

Код:
#include <iostream>
#include <fstream>
struct Product
{
    int id;
    string name;
    string upc;
    string manufact;
    double price;
    int save;
    int count;
};
ofstream fout("out.txt");
void f1(Product arr[], string name)
{
    for (int i = 0; i < sizeof arr; ++i)
    {
        if (arr[i].name == name)
        {
            fout << "id:" << arr[i].id;
            fout << "\tName:" << arr[i].name;
            fout << "\tType:" << arr[i].upc;
            fout << "\tManufactor:" << arr[i].manufact;
            fout << "\tPrice:" << arr[i].price << "USD";
            fout << "\tTerm:" << arr[i].save << "Days";
            fout << "\tQuantity:" << arr[i].count;
        }
    }
}
void f2(Product arr[], string name, double price)
{
    for (int i = 0; i < sizeof arr; ++i)
    {
        if (arr[i].name == name && price >= arr[i].price)
        {
            fout << "id:" << arr[i].id;
            fout << "\tName:" << arr[i].name;
            fout << "\tType:" << arr[i].upc;
            fout << "\tManufactor:" << arr[i].manufact;
            fout << "\tPrice:" << arr[i].price << "USD";
            fout << "\tTerm:" << arr[i].save << "Days";
            fout << "\tQuantity:" << arr[i].count;
        }
    }
}
void f3(Product arr[], int save)
{
    for (int i = 0; i < sizeof arr; ++i)
    {
        if (save < arr[i].save)
        {
            fout << "id:" << arr[i].id;
            fout << "\tName:" << arr[i].name;
            fout << "\tType:" << arr[i].upc;
            fout << "\tManufactor:" << arr[i].manufact;
            fout << "\tPrice:" << arr[i].price << "USD";
            fout << "\tTerm:" << arr[i].save << "Days";
            fout << "\tQuantity:" << arr[i].count;
        }
    }
}

int main()
{
    ifstream fin("input.txt");
    int n = 0;
    fin >> n;
    Product ptd[n];

    for (int i = 0; i < n; ++i)
    {
        fin >> ptd[i].id;
        fin >> ptd[i].name;
        fin >> ptd[i].upc;
        fin >> ptd[i].manufact;
        fin >> ptd[i].price;
        fin >> ptd[i].save;
        fin >> ptd[i].count;
    }

    ofstream sav("save.txt");
    for (int i = 0; i < n; ++i)
    {
        sav << "id:" << ptd[i].id;
        sav << "\tName:" << ptd[i].name;
        sav << "\tType:" << ptd[i].upc;
        sav << "\tManufactor:" << ptd[i].manufact;
        sav << "\tPrice:" << ptd[i].price << "USD";
        sav << "\tTerm:" << ptd[i].save << "Days";
        sav << "\tQuantity:" << ptd[i].count << '\n';
    }
    sav.close();

    fout << "Enter name product:\n";
    string name;
    fin >> name;
    f1(ptd, name);

    fout << '\n';

    fout << "Enter name product:\n";
    string _name;
    fin >> _name;
    fout << "Enter price product:\n";
    int price;
    fin >> price;
    f2(ptd, _name, price);

    fout << '\n';

    fout << "Enter term product:\n";
    int save;
    fin >> save;
    f3(ptd, save);

    fin.close();
    fout.close();
    return 0;
}
Данные файла "input.txt"
5
0 Milk 1234511 UK_Ltd. 4.35 7 5
1 Pepsi 1234512 UK_Ltd. 5.85 180 8
2 Coca-Cola 1234513 USA_Ltd. 3.65 180 6
3 Pepsi 1234514 USA_Ltd. 7.28 180 4
4 Pepsi 1234515 USA_Ltd. 10.00 180 2
Milk
Pepsi
10
7

Помогите пожалуйста переделать код C/C++ под Kotlin
faktor вне форума Ответить с цитированием
Старый 25.03.2023, 08:53   #2
Алексей1153
фрилансер
Форумчанин
 
Регистрация: 11.10.2019
Сообщений: 947
По умолчанию

faktor, что значит "переделать"?

--
а, всё, увидел. Это в названии темы надо писать ))
Алексей1153 вне форума Ответить с цитированием
Старый 01.04.2023, 22:14   #3
Bugrimov
C/C++, Java
Участник клуба
 
Аватар для Bugrimov
 
Регистрация: 28.03.2012
Сообщений: 1,680
По умолчанию

Код:
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.OutputStreamWriter
import java.math.BigDecimal

private const val INPUT_TXT = "input.txt"
private const val OUT_TXT = "out.txt"
private const val SAVE_TXT = "save.txt"

private typealias ProductFilter = (Product) -> Boolean

fun main() {
    try {
        File(INPUT_TXT).bufferedReader().use {

            val products = it.toProducts()
            val reports = it.toReports()

            File(OUT_TXT)
                .writer()
                .reports(products, reports)
                .writeDown()

            File(SAVE_TXT)
                .writer()
                .products(products)
                .writeDown()
        }
    } catch (ex: IOException) {
        println(ex.message)
    }
}

private fun OutputStreamWriter.reports(products: List<Product>, reports: List<Report>): OutputStreamWriter {
    reports.forEach {
        this.title(it.title)
        this.products(products, it.filter)
    }
    return this
}

private fun BufferedReader.toReports(): List<Report> {
    val productNameOne = this.readLine()
    val productNameTwo = this.readLine()
    val productPrice = this.readLine().toBigDecimal()
    val productSave = this.readLine().toInt()
    return listOf(
        Report("Enter product name:") { product: Product -> product.name == productNameOne },
        Report("Enter name and price product:") { product -> product.name == productNameTwo && product.price <= productPrice },
        Report("Enter term product:") { product -> product.save > productSave }
    )
}

private fun BufferedReader.toProducts(): List<Product> {
    return  IntRange(1, this.readLine().toInt()).map {
        this.readLine().split(" ").toProduct()
    }
}

private fun OutputStreamWriter.title(line: String): OutputStreamWriter {
    this.appendLine(line)
    return this
}

private fun OutputStreamWriter.products(products: List<Product>, filter: (Product) -> Boolean = { _ -> true }): OutputStreamWriter {
    products
        .filter(filter)
        .forEach { this.append(it.toLine()) }
    return this
}

private fun OutputStreamWriter.writeDown() {
    this.flush()
    this.close()
}

private fun List<String>.toProduct(): Product {
    return Product(
        this[0].toInt(),
        this[1],
        this[2],
        this[3],
        this[4].toBigDecimal(),
        this[5].toInt(),
        this[6].toInt()
    )
}

private data class Product(
    val id: Int,
    val name: String,
    val upc: String,
    val manufacture: String,
    val price: BigDecimal,
    val save: Int,
    val count: Int
) {

    fun toLine() =
        "id: $id\tName: $name\tType: $upc\tManufacture: $manufacture\tPrice: $price USD\tTerm: $save days\tQuantity: $count\n"
}

private data class Report(
    val title: String,
    val filter: ProductFilter
)
Отчет получается такой (out.txt):
Код:
Enter product name:
id: 0	Name: Milk	Type: 1234511	Manufacture: UK_Ltd.	Price: 4.35 USD	Term: 7 days	Quantity: 5
Enter name and price product:
id: 1	Name: Pepsi	Type: 1234512	Manufacture: UK_Ltd.	Price: 5.85 USD	Term: 180 days	Quantity: 8
id: 3	Name: Pepsi	Type: 1234514	Manufacture: USA_Ltd.	Price: 7.28 USD	Term: 180 days	Quantity: 4
id: 4	Name: Pepsi	Type: 1234515	Manufacture: USA_Ltd.	Price: 10.00 USD	Term: 180 days	Quantity: 2
Enter term product:
id: 1	Name: Pepsi	Type: 1234512	Manufacture: UK_Ltd.	Price: 5.85 USD	Term: 180 days	Quantity: 8
id: 2	Name: Coca-Cola	Type: 1234513	Manufacture: USA_Ltd.	Price: 3.65 USD	Term: 180 days	Quantity: 6
id: 3	Name: Pepsi	Type: 1234514	Manufacture: USA_Ltd.	Price: 7.28 USD	Term: 180 days	Quantity: 4
id: 4	Name: Pepsi	Type: 1234515	Manufacture: USA_Ltd.	Price: 10.00 USD	Term: 180 days	Quantity: 2
Все данные (save.txt)
Код:
id: 0	Name: Milk	Type: 1234511	Manufacture: UK_Ltd.	Price: 4.35 USD	Term: 7 days	Quantity: 5
id: 1	Name: Pepsi	Type: 1234512	Manufacture: UK_Ltd.	Price: 5.85 USD	Term: 180 days	Quantity: 8
id: 2	Name: Coca-Cola	Type: 1234513	Manufacture: USA_Ltd.	Price: 3.65 USD	Term: 180 days	Quantity: 6
id: 3	Name: Pepsi	Type: 1234514	Manufacture: USA_Ltd.	Price: 7.28 USD	Term: 180 days	Quantity: 4
id: 4	Name: Pepsi	Type: 1234515	Manufacture: USA_Ltd.	Price: 10.00 USD	Term: 180 days	Quantity: 2
"Keep it simple" - придерживайтесь простоты!
Уильям Оккам - "Не следует множить сущее без необходимости"
Сложность - враг простоты и удобства!

Последний раз редактировалось Bugrimov; 01.04.2023 в 23:38.
Bugrimov вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
C/C++ помогите пожалуйста переделать код faktor Помощь студентам 2 21.03.2023 07:18
Помогите пожалуйста переделать код в ООП user12102018 JavaScript, Ajax 1 13.10.2018 20:31
Помогите переделать код под мое условие пожалуйста Desheg Помощь студентам 1 21.05.2018 19:56
Помогите,пожалуйста,переделать программу. vep Общие вопросы C/C++ 5 19.10.2009 00:35
Помогите пожалуйста переделать прогу barbossa Общие вопросы C/C++ 1 08.06.2009 13:10