문제
그래서 교사는이 과제를 제기했습니다.
법 집행을 위해 United Network 명령에 의해 고용되었으며, 해독 해야하는 Null Cyphers가 포함 된 파일이 제공되었습니다.
따라서 (예를 들어) 첫 번째 파일의 경우 다른 모든 문자가 정확합니다 (예 : 'hielqlpo' 폴더의 데스크탑에 있고 파일의 이름이 document01.cry입니다. 해당 파일을 프로그램에 넣어야하는 명령이 확실하지 않습니다.
나는 또한 편지를 잡고 편지를 건너 뛰는 방법을 지나치게 잘 모르겠지만 솔직히 그 질문을 게시하기 전에 그것에 땜질하고 싶습니다! 그래서 지금은 ... 제 질문은 제목에 언급되었습니다. C ++에서 읽기위한 파일을 어떻게 잡습니까?
그것이 차이가 있다면 (확실히 그렇듯이) Visual C ++ 2008 Express Edition을 사용하고 있습니다 (무료이고 마음에 들기 때문에! 지금까지 가지고있는 것을 첨부했습니다. 매우 기본 ... 그리고 나는 그것을 추가했다 getchar();
끝에 제대로 작동 할 때 창이 열려있어 볼 수 있습니다 (Visual Express가 창을 닫는 즉시 창을 닫는 경향이 있으므로).
지금까지 코드 :
#include<iostream>
using namespace std;
int main()
{
while (! cin.eof())
{
int c = cin.get() ;
cout.put(c) ;
}
getchar();
}
추신 : 나는이 코드가 모든 캐릭터를 잡고 내린다는 것을 알고 있습니다. 지금은 괜찮습니다. 일단 파일을 읽을 수 있으면 거기에서 땜질 할 수 있다고 생각합니다. 나는 또한 C ++에있는 책을 한두 번 찔러서 무엇이든 나타나서 "나를 선택하십시오!" 다시 한 번 감사드립니다!
편집 :: 또한 호기심이 많으므로 원하는 파일을 입력하는 방법이 있습니까? (즉:
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);
이 코드는 작동하지 않습니다. Char가 const char *로 변환 될 수 없다는 오류를 촬영합니다. 이 문제는 어떻게 해결할 수 있습니까?
편집 2 : Part 2에 대해 신경 쓰지 마십시오. 나는 그것을 발견했습니다! 도움을 주셔서 다시 한 번 감사드립니다!
해결책 5
나는 그것을 알아! 솔직히 말해서 아무도 대답하지 않아도, 그것은 세 가지의 조합과 그들로부터의 의견이었다. 정말 감사합니다! 내가 사용한 코드와 문서 사본을 첨부했습니다. 이 프로그램은 모든 캐릭터에서 읽은 다음 해독 된 텍스트를 뱉어냅니다. (IE : 1H.E0L/LQO는 Hello입니다) 다음 단계 (추가 크레딧)는 다음 단계를 설정하여 다음 문자가 다음 문자를 읽기 전에 건너 뛰는 문자 수를 입력하여 입력을 설정하는 것입니다.
이 단계는 스스로해야하지만 다시 한번, 모든 사람들에게 모든 도움을 주셔서 대단히 감사합니다! 이 사이트가 얼마나 멋진 지 다시 한 번, 한 번에 한 줄의 코드를 증명합니다!
편집 :: 코드는 사용자 입력을 수락하도록 조정하고, 다시 컴파일하지 않고 여러 용도를 허용 할 수 있습니다 (나는 그것이 거대한 조잡한 엉망인 것처럼 보이지만, 그것이 매우 댓글이 많이있는 이유입니다 ... 내 마음 속에는 멋지고 깔끔해 보이기 때문에).
#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.
}
편집하다:::
텍스트를 삽입하려고 시도했지만 제대로 나올 수 없었습니다. 코딩과 같은 일부 캐릭터를 계속 처리했습니다 (예 : Apostrophe는 분명히 대담한 명령과 동일합니다). .l9lao ".txt로 괄호가없는. 동일한 결과를 제공해야합니다.
도움을 주신 모든 분들께 다시 한 번 감사드립니다!
다른 팁
파일 작업을 수행하려면 올바른 다음 포함이 필요합니다.
#include <fstream>
그런 다음 기본 기능에서 파일 스트림을 열 수 있습니다.
ifstream inFile( "filename.txt", ios::in );
또는 출력의 경우 :
ofstream outFile( "filename.txt", ios::out );
그런 다음 CIN을 사용하는 것처럼 Infile을 사용할 수 있으며 Cout을 사용하는 것처럼 Outfile을 사용할 수 있습니다. 완료되면 파일을 닫으려면 :
inFile.close();
outFile.close();
편집] 명령 줄 인수에 대한 지원 포함 [편집] 수정 가능한 메모리 누출 [편집] 누락 된 참조 수정
#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;
}
트릭을해야합니다. 파일이 매우 크면 전체 파일을 버퍼에로드해서는 안됩니다.
퀘스트가 응답되었지만 두 가지 작은 팁 : 1) X와 Y를 계산하는 대신 홀수 또는 캐릭터에 있는지 확인하십시오. 다음을 수행 할 수 있습니다.
int count=0;
while(!infile.eof())
{
infile.get(letter);
count++;
if(count%2==0)
{
cout<<letter;
}
}
%는 본질적으로 '나머지로 나뉘어 질 때 나머지'를 의미하므로 11% 3은 2입니다. 위에서는 이상하거나 균일합니다.
2) Windows에서만 실행하면됩니다.
system("pause");
실행이 완료되면 창을 열어두면 마지막 getchar () 호출이 필요하지 않습니다 ( #include<Windows.h>
그것이 작동하기 위해).