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

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

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

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

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

Ответ
 
Опции темы Поиск в этой теме
Старый 13.03.2015, 05:33   #1
WhiteJoker
Пользователь
 
Регистрация: 26.10.2014
Сообщений: 10
По умолчанию Исключение std::ios_base::failure basic_ios::clear

Код компилится но прога вылетает

Код:
    #include <iostream>
	#include <iomanip>
	#include <fstream>
	#include <string>
	 
	using namespace std;
	const int ARRAYSIZE = 26;
	const char alphabet[ARRAYSIZE] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	
	void characterCount(char ch, int list[]);
	void calcShift( int& shift, int list[]);
	void writeOutput(ifstream &in, ofstream &out, int shift);
	 
	int main()
	{
	    int asciiCode = 0,
	        shift = 0;
	    string filename;
	    char ch;
	    ifstream infile;
	    ofstream outfile;
	    string reply;
	 
	    //input file
	 
	    infile.open("Ceasarencryptfile.txt", std::ios::out | std::ios::binary);
	    infile.exceptions ( ifstream::badbit );
        //try {
	        if (!infile.is_open()) { 
	 
	            cout << "Unable to open file or it doesn't exist." << endl;
	 
	            return 1;
	 
	        }
	    //output file
	 
	 
	 
	    outfile.open("outputhack");
	 
	    int list[ARRAYSIZE] = {0}; 
	 
	        while (infile)//(infile.peek() != EOF) 
	        {
	            infile.get(ch);
	            characterCount(ch, list); 
	        }
	    //}
	    //catch (ifstream::failure e){}

	 
	 
	 
	    infile.clear();
	    infile.seekg(0);
	    
	    calcShift (shift, list);
	    writeOutput(infile, outfile, shift); 
	 
	    return 0;
	    outfile.close();
		
	}
	 
	void characterCount(char ch, int list[])
	{
		for (unsigned int i = 0; i <= ARRAYSIZE; i++)
		{
	        if (ch == alphabet[i])//(ch >= 'A' && ch <= 'z') 
	        {
	            int asciiCode = 0;
 
	            asciiCode = static_cast<int>(ch); 
	            list[asciiCode]++; 
	        }
	    }    
	}
	 
	void calcShift( int& shift, int list[])
	{
	    int maxIndex = 0; 
	 
	    for (unsigned int i = 0; i <= ARRAYSIZE; i++)
	    {
	        if (list[maxIndex] < list[i])
	                maxIndex = i; 
	    }
	 
	    for (unsigned int i = 0; i <= ARRAYSIZE; i++)
	    {
	    if (maxIndex == alphabet[i])//(maxIndex >= 'A' && maxIndex <= 'Z') 
		    shift = 'E' - maxIndex;
	 
	    /*if (maxIndex >= 'a' && maxIndex <= 'z') 
	        shift = 'e' - maxIndex;*/
		}
	}
	 
	void writeOutput(ifstream &infile, ofstream &outfile, int shift)
	{
	    char ch;
	 
	    while (infile)/*(infile.peek() != EOF)*/ { 
	 
	        infile.get(ch);
			for (unsigned int i = 0; i <= ARRAYSIZE; i++)
			{ 
	 
	            if (ch == alphabet[i])//(ch >= 'A' && ch <= 'Z')
	            {
	                ch = 'A' + (((ch - 'A') + shift + 26) % 26);
	            }
	        /*    if (ch >= 'a' && ch <= 'z') 
	            {
	                ch = 'a' + (((ch - 'a') + shift + 26) % 26);
	            }*/
	        }    
	 
	        outfile << ch; //Print to the outfile
	        cout << ch;
	         
	    }
	}
в чем проблема?? не могу понять где я за границы массивов вышел
WhiteJoker вне форума Ответить с цитированием
Старый 14.03.2015, 03:23   #2
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Код:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;
const int ARRAYSIZE = 26;

void characterCount(char ch, int list[]);
void calcShift(int& shift, int list[]);
void writeOutput(ifstream &in, ofstream &out, int shift);

int main()
{
    int shift = 0;
    char ch;
    ifstream infile;
    ofstream outfile;
    infile.open("Ceasarencryptfile.txt", std::ios::out | std::ios::binary);
    if (!infile.is_open()) {
        cout << "Unable to open file or it doesn't exist." << endl;
        return 1;
    }
    outfile.open("outputhack.txt");
    int list[ARRAYSIZE] = {0};
    while (infile.get(ch))
        characterCount(ch, list);
    infile.clear();
    infile.seekg(0);
    calcShift(shift, list);
    writeOutput(infile, outfile, shift);
    infile.close();
    outfile.close();
    return 0;
}

void characterCount(char ch, int list[])
{
    if (ch >= 'A' && ch <= 'Z')
        ++list[ch - 'A'];
}

void calcShift(int &shift, int list[])
{
    int maxIndex = 0;
    for (unsigned int i = 1; i < ARRAYSIZE; ++i)
        if (list[maxIndex] < list[i])
            maxIndex = i;
    shift = 'E' - 'A' - maxIndex;
}

void writeOutput(ifstream &infile, ofstream &outfile, int shift)
{
    char ch;
    while (infile.get(ch)) {
        if (ch >= 'A' && ch <= 'Z')
            ch = 'A' + (((ch - 'A') + shift + 26) % 26);
        outfile << ch;
        cout << ch;
    }
}
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )

Последний раз редактировалось BDA; 14.03.2015 в 03:26.
BDA на форуме Ответить с цитированием
Старый 14.03.2015, 23:39   #3
WhiteJoker
Пользователь
 
Регистрация: 26.10.2014
Сообщений: 10
По умолчанию

Спасибо
а можно зделать так чтобы в циклах я сверялся не с таблицей символов а с массивом алфавита который состоит из нужных мне символов???
WhiteJoker вне форума Ответить с цитированием
Старый 15.03.2015, 00:53   #4
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Код:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

const char alphabet[] = {'A','B','C','E'};
const int E_IND = 3;
const int ARRAYSIZE = sizeof(alphabet) / sizeof(alphabet[0]);

void characterCount(char ch, int list[]);
void calcShift(int& shift, int list[]);
void writeOutput(ifstream &in, ofstream &out, int shift);

int main()
{
    int shift = 0;
    char ch;
    ifstream infile;
    ofstream outfile;
    infile.open("Ceasarencryptfile.txt", std::ios::out | std::ios::binary);
    if (!infile.is_open()) {
        cout << "Unable to open file or it doesn't exist." << endl;
        return 1;
    }
    outfile.open("outputhack.txt");
    int list[ARRAYSIZE] = {0};
    while (infile.get(ch))
        characterCount(ch, list);
    infile.clear();
    infile.seekg(0);
    calcShift(shift, list);
    writeOutput(infile, outfile, shift);
    infile.close();
    outfile.close();
    return 0;
}

void characterCount(char ch, int list[])
{
    for (int i = 0; i < ARRAYSIZE; ++i)
        if (ch == alphabet[i]) {
            ++list[i];
            break;
        }
}

void calcShift(int &shift, int list[])
{
    int maxIndex = 0;
    for (unsigned int i = 1; i < ARRAYSIZE; ++i)
        if (list[maxIndex] < list[i])
            maxIndex = i;
    shift = E_IND - maxIndex;
}

void writeOutput(ifstream &infile, ofstream &outfile, int shift)
{
    char ch;
    while (infile.get(ch)) {
        for (int i = 0; i < ARRAYSIZE; ++i)
            if (ch == alphabet[i]) {
                ch = alphabet[(i + shift + ARRAYSIZE) % ARRAYSIZE];
                break;
            }
        outfile << ch;
        cout << ch;
    }
}
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )
BDA на форуме Ответить с цитированием
Старый 16.03.2015, 00:33   #5
WhiteJoker
Пользователь
 
Регистрация: 26.10.2014
Сообщений: 10
По умолчанию

спасибо!!! буду пробовать)))

Еще хочу спросить можно ли переделать програму так чтобы она взламывала шифр простой замены??? Если да то как??

Последний раз редактировалось Stilet; 16.03.2015 в 07:49.
WhiteJoker вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
ios_base (c++) Nonamelol Помощь студентам 1 21.10.2013 06:09
Explorer.exe Исключение неизвестное программное исключение Windows XP, что делать? Igorilla Windows 6 02.04.2013 22:49
ios_base::binary что значит? Aztek93 Общие вопросы C/C++ 1 02.06.2012 19:45
Исключение при удалении из std::map arokot Общие вопросы C/C++ 2 11.08.2010 17:36
ошибка: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits<char> Critter Общие вопросы C/C++ 5 08.08.2010 23:38