Pregunta

Entonces el maestro ha planteado esta tarea:

Usted ha sido contratado por United Network Command for Law Enforcement, y le han dado archivos que contienen cifrados nulos que debe descifrar.

Entonces, para el primer archivo dado (como ejemplo), todas las demás letras son correctas (es decir: 'hielqlpo' es hola (suponiendo que comience con la primera letra). Mi primera pregunta es, ¿cómo leo en un archivo? ? El documento está en mi escritorio en una carpeta y el archivo se llama document01.cry. No estoy seguro del comando que necesito para poner ese archivo en el programa.

Tampoco estoy muy seguro de cómo tomar una carta y omitirla, pero honestamente, quiero jugar con eso antes de publicar esa pregunta. Entonces, por ahora ... mi pregunta es como se indica en el título: ¿Cómo se toma un archivo para leer en C ++?

Si hace la diferencia (como estoy seguro), estoy usando Visual C ++ 2008 Express Edition (¡porque es gratis y me gusta! También he adjuntado lo que tengo hasta ahora, por favor manténgalo importa que es muy básico ... y agregué el getchar(); al final para que cuando se ejecute correctamente, la ventana permanezca abierta para que pueda verla (ya que Visual Express tiende a cerrar la ventana tan pronto como termina de ejecutarse) .)

El código hasta ahora:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PD: Me doy cuenta de que este código agarra y saca todos los caracteres. Por ahora está bien, una vez que puedo leer el archivo, creo que puedo jugar desde allí. También estoy hurgando en un libro o dos que tengo en C ++ para ver que algo aparece y grita & "; ¡Cógeme! &"; Gracias de nuevo!

EDITAR :: También es curioso, ¿hay alguna forma de ingresar el archivo que desea? (Es decir:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

Este código no funciona. Devuelve un error que dice que el char no se puede convertir en un const char *. ¿Cómo se puede solucionar este problema?

EDITAR 2: No importa sobre dicha parte 2, ¡lo descubrí! Gracias de nuevo por la ayuda!

¿Fue útil?

Solución 5

¡Lo descubrí! Para ser sincero, ninguna respuesta ayudó, fue una combinación de los tres, más los comentarios de ellos. ¡Muchas gracias a todos! He adjuntado el código que utilicé, así como una copia del documento. El programa lee en cada carácter, luego escupe el texto descifrado. (IE: 1h.e0l / lqo es hola) El siguiente paso (crédito adicional) es configurarlo para que el usuario ingrese cuántos caracteres omitir antes de leer el siguiente carácter para ingresar.

Este paso tengo la intención de hacerlo por mi cuenta, pero nuevamente, ¡muchas gracias por toda la ayuda a todos! Demostrando una vez más lo increíble que es este sitio, ¡una línea de código a la vez!

EDITAR :: Código ajustado para aceptar la entrada del usuario, así como para permitir múltiples usos sin recompilar (me doy cuenta de que parece un gran desorden descuidado, pero es por eso que está COMENTADO EXTREMADAMENTE ... porque en mi opinión se ve bien y ordenado)

#include<iostream>
#include<fstream>   //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    program:
    char choice;  //lets user choose whether to do another document or not.
    char letter;  //used to track each character in the document.
    int x = 1;    //first counter for tracking correct letter.
    int y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
    int z;        //third counter (used as a check to see if the first two counters are equal).
    string filename;    //allows for user to input the filename they wish to use.
    cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
    cin >> filename; //getline(cin, filename);
    cout << endl;
    cout << "'Every nth character is good', what number is n?: ";
    cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
    cout << endl;
    z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
    ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
    if(infile.is_open()) //checks to see if the file is opened.
    {
        while(!infile.eof())    //continues looping until the end of the file.
        {   
                infile.get(letter);  //gets the letters in the order that that they are in the file.
                if (x == y)          //checks to see if the counters match...
                {
                    x++;             //...if they do, adds 1 to the x counter.
                }
                else
                {
                    if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                    {
                        cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                        y = x;                  //sets both counters equal to restart the process of counting.
                    }
                    else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                    {                           //counter until the first and second counters are equal.
                        x++;
                    }
                }
        }
        cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl;
        infile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive).";
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    else  //this prints out and program is skipped in case an incorrect file name is used.
    {
        cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
        cout << "IE:" << "     filename.txt" << endl;
        cout << "You input: " << filename << endl;
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    getchar();  //because I use visual C++ express.
}

EDITAR :::

Traté de insertar el texto, pero no pude hacerlo salir bien, seguía tratando algunos de los caracteres como codificación (es decir, un apóstrofe aparentemente es el equivalente del comando en negrita), pero podría intentar poner en " 0h1e.l9lao " sin el paréntesis en un .txt y debería dar el mismo resultado.

¡Gracias de nuevo a todos por la ayuda!

Otros consejos

Para realizar operaciones de archivo, necesita la inclusión correcta:

#include <fstream>

Luego, en su función principal, puede abrir una secuencia de archivos:

ifstream inFile( "filename.txt", ios::in );

o, para salida:

ofstream outFile( "filename.txt", ios::out );

Luego puede usar inFile como usaría cin, y outFile como usaría cout. Para cerrar el archivo cuando haya terminado:

inFile.close();
outFile.close();

[EDITAR] incluye soporte para argumentos de línea de comando [EDITAR] Se corrigió la posible pérdida de memoria [EDITAR] Se corrigió una referencia faltante

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv){
    ifstream infh;  // our file stream
    char *buffer;

    for(int c = 1; c < argc; c++){
        infh.open(argv[c]);

        //Error out if the file is not open
        if(!infh){
            cerr << "Could not open file: "<< argv[c] << endl;
            continue;
        }

        //Get the length of the file 
        infh.seekg(0, ios::end);
        int length = infh.tellg();

        //reset the file pointer to the beginning
        is.seekg(0, ios::beg);

        //Create our buffer
        buffer = new char[length];

        // Read the entire file into the buffer
        infd.read(buffer, length);

        //Cycle through the buffer, outputting every other char
        for(int i=0; i < length; i+= 2){
            cout << buffer[i]; 
        }
        infh.close();
    }
    //Clean up
    delete[] buffer;
    return 0;
}

Debería hacer el truco. Si el archivo es extremadamente grande, probablemente no debería cargar todo el archivo en el búfer.

Aunque su pregunta ha sido respondida, dos pequeños consejos: 1) En lugar de contar xey para ver si estás en un personaje par o impar, puedes hacer lo siguiente:

int count=0;
while(!infile.eof())
{       
    infile.get(letter);
    count++;
    if(count%2==0)
    {
        cout<<letter;
    }
}

% significa esencialmente 'resto cuando se divide por', entonces 11% 3 es dos. en lo anterior da impar o par.

2) Suponiendo que solo necesita ejecutarlo en Windows:

system("pause");

hará que la ventana permanezca abierta cuando termine de ejecutarse para que no necesite la última llamada getchar () (puede que tenga que #include<Windows.h> para que eso funcione).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top