Convertidor Simple De C A C#

Este programa está diseñado para convertir programas C sencillos a código C#. Toma un programa C como entrada y lo traduce a un programa C# correspondiente que se compila y ejecuta correctamente. El convertidor realiza conversiones básicas para construcciones comunes de C, como printf, scanf, tipos int y estructuras de control. Debería manejar programas sencillos, pero para código C más complejo, puede que se requieran ajustes manuales. Por ejemplo, la sentencia printf en C se convierte a Console.WriteLine en C#, y scanf se reemplaza por Console.ReadLine.

Grupo

Manejo de archivos en C#

Objectivo

1. Introduzca un programa simple en C para la conversión.
2. El programa traducirá automáticamente el código C a C#.
3. La conversión incluirá la sustitución de las funciones de la biblioteca estándar de C por equivalentes en C#.
4. El programa en C# convertido se generará en un nuevo archivo.
5. Pruebe el programa convertido con diferentes programas en C para garantizar la compatibilidad.

Cree un programa para convertir programas simples en C, como el siguiente, a C#.

Nota: El programa resultante debe compilarse correctamente. Pruébelo con otros programas en C similares.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;
using System.IO;

class CtoCSharpConverter
{
    // Main method where the program starts execution
    static void Main(string[] args)
    {
        // Prompt the user to input the path of the C file to convert
        Console.WriteLine("Enter the path of the C program:");
        string cFilePath = Console.ReadLine();

        // Check if the C file exists
        if (!File.Exists(cFilePath))
        {
            Console.WriteLine("The specified C file does not exist.");
            return;
        }

        try
        {
            // Read the contents of the C file
            string cProgramCode = File.ReadAllText(cFilePath);

            // Convert C program to C# program
            string cSharpProgram = ConvertCtoCSharp(cProgramCode);

            // Define the output file path (same as input file but with ".cs" extension)
            string cSharpFilePath = Path.ChangeExtension(cFilePath, ".cs");

            // Save the converted C# program to a new file
            File.WriteAllText(cSharpFilePath, cSharpProgram);

            // Output success message and path of the generated C# file
            Console.WriteLine("Conversion successful! The C# program has been saved to:");
            Console.WriteLine(cSharpFilePath);
        }
        catch (Exception ex)
        {
            // Handle any errors that occur during file reading or writing
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    // Method to convert a simple C program to C#
    static string ConvertCtoCSharp(string cProgram)
    {
        // Replace C 'printf' with C# 'Console.WriteLine'
        string cSharpProgram = cProgram.Replace("printf", "Console.WriteLine");

        // Replace C 'scanf' with C# 'Console.ReadLine'
        cSharpProgram = cSharpProgram.Replace("scanf", "Console.ReadLine");

        // Replace C 'int' with C# 'int' (this is actually the same in both languages)
        // Add conversion rules for more complex scenarios as needed

        // Convert the 'main' method signature from C to C#
        cSharpProgram = cSharpProgram.Replace("int main()", "static void Main()");

        // Replace C-style comment '/* ... */' with C#-style comments
        cSharpProgram = cSharpProgram.Replace("/*", "//").Replace("*/", "");

        // Convert return type and statements for C#
        cSharpProgram = cSharpProgram.Replace("return 0;", "// return 0;");

        return cSharpProgram;
    }
}

 Output

//For a simple C program like:
#include 

int main() {
    printf("Hello, World!\n");
    return 0;
}

//The output C# program would be:
using System;

class Program
{
    static void Main() {
        Console.WriteLine("Hello, World!");
    }
}

Comparte este ejercicio de C#