Domanda

Quindi l'insegnante ha proposto questo incarico:

Sei stato assunto dal United Network Command for Law Enforcement e ti sono stati dati file contenenti null cyphers che devi decrittografare.

Quindi, per il primo file fornito (come esempio), ogni altra lettera è corretta (cioè: 'hielqlpo' è ciao (supponendo che inizi con la prima lettera). La mia prima domanda è, come posso leggere in un file ? Il documento si trova sul mio desktop in una cartella e il file si chiama document01.cry. Non sono sicuro del comando che devo inserire nel file.

Inoltre non sono troppo sicuro di come prendere una lettera e saltare una lettera, ma onestamente voglio armeggiare con quello prima di pubblicare quella domanda! Quindi per ora ... la mia domanda è come indicato nel titolo: Come si ottiene un file per la lettura in C ++?

Se fa la differenza (come sono sicuro), sto usando Visual C ++ 2008 Express Edition (perché è gratuito e mi piace! Ho anche allegato ciò che ho finora, per favore continua a mente è molto basilare ... e alla fine ho aggiunto getchar(); quindi quando funziona correttamente, la finestra rimane aperta in modo che io possa vederla (poiché Visual Express tende a chiudere la finestra non appena è stata eseguita .)

Il codice finora:

#include<iostream>

using namespace std;

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

PS: mi rendo conto che questo codice prende e mette fuori ogni carattere. Per ora va bene, una volta che posso leggere il file penso di poter armeggiare con esso da lì. Sto anche frugando in uno o due libri che ho su C ++ per vederlo apparire e urlare & Quot; Pick me! & Quot; Grazie ancora!

EDIT :: Anche curioso, c'è un modo per inserire il file che desideri? (Vale a dire:.

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);

Questo codice non funziona. Risolve un errore che dice che il carattere non può essere convertito in un carattere costante *. Come si può risolvere questo problema?

MODIFICA 2: Non importa per la seconda parte, l'ho scoperto! Grazie ancora per l'assistenza!

È stato utile?

Soluzione 5

L'ho capito! Ad essere sinceri, nessuna risposta ha aiutato, era una combinazione dei tre, più i commenti da loro. Grazie mille a tutti! Ho allegato il codice che ho usato, nonché una copia del documento. Il programma legge ogni carattere, quindi sputa il testo decifrato. (IE: 1h.e0l / lqo is hello) Il passaggio successivo (credito extra) è di configurarlo in modo che l'utente immetta quanti caratteri saltare prima di leggere il carattere successivo da inserire.

Questo passo intendo fare da solo, ma ancora una volta, grazie mille per l'assistenza a tutti! Dimostrando ancora una volta quanto è fantastico questo sito, una riga di codice alla volta!

EDIT :: Codice modificato per accettare l'input dell'utente, oltre a consentire più usi senza ricompilare (mi rendo conto che sembra un enorme pasticcio sciatto, ma è per questo che è ESTREMAMENTE commentato ... perché nella mia mente sembra carino e pulito)

#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.
}

EDIT :::

Ho provato a inserire il testo, ma non riuscivo a farlo uscire bene, continuava a trattare alcuni dei personaggi come la codifica (cioè un apostrofo apparentemente è l'equivalente del comando in grassetto), ma potresti semplicemente provare a mettere tra " 0h1e.l9lao " senza la parentesi in un .txt e dovrebbe dare lo stesso risultato.

Grazie ancora a tutti per l'aiuto!

Altri suggerimenti

Per eseguire le operazioni sui file, è necessario includere correttamente:

#include <fstream>

Quindi, nella tua funzione principale, puoi aprire un flusso di file:

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

o, per l'output:

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

È quindi possibile utilizzare inFile come si userebbe cin e outFile come si userebbe cout. Per chiudere il file al termine:

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

[EDIT] include il supporto per gli argomenti della riga di comando [EDIT] Risolto possibile perdita di memoria [EDIT] Risolto un riferimento mancante

#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;
}

Dovrebbe fare il trucco. Se il file è estremamente grande, probabilmente non dovresti caricare l'intero file nel buffer.

Sebbene la tua queston abbia ricevuto risposta, due piccoli consigli: 1) Invece di contare xey per vedere se sei su un personaggio pari o dispari puoi fare quanto segue:

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

% significa essenzialmente "resto se diviso per", quindi l'11% 3 è due. nel precedente dà pari o dispari.

2) Supponendo che sia necessario eseguirlo solo su Windows:

system("pause");

manterrà la finestra aperta al termine della sua esecuzione, quindi non è necessaria l'ultima chiamata getchar () (potrebbe essere necessario #include<Windows.h> affinché funzioni).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top