2015-10-14 2 views
0

У меня, похоже, проблема, похожая на сообщение здесь: Confusing "std::out_of_range" Error. Моя проблема в том, что я не могу понять, где/как мне нужно исправить проблему. Вот мой код, и я отправлю ошибку ниже.C++ Visual Studio за пределами допустимой погрешности

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 
//In this program we are going to make a secret code decoder. 
int main() { 
    /*char a = '!'; 
    char b = '^'; 
    char c = '&'; 
    char d = '*'; 
    char e = '@'; 
    char f = '('; 
    char g = ')'; 
    char h = '-'; 
    char i = '#'; 
    char j = '_'; 
    char k = '='; 
    char l = '+'; 
    char m = '['; 
    char n = '{'; 
    char o = '$'; 
    char p = ']'; 
    char q = '}'; 
    char r = ';'; 
    char s = ':'; 
    char t = ','; 
    char u = '%'; 
    char v = '<'; 
    char w = '.'; 
    char x = '>'; 
    char y = '/'; 
    char z = '?';*/ 

    // Now for the tedious part... declaring variables for the 26 letters of the alphabet, and searching the string and replacing... :p 

    int A = 0; 
    int B = 0; 
    int C = 0; 
    int D = 0; 
    int E = 0; 
    int F = 0; 
    int G = 0; 
    int H = 0; 
    int I = 0; 
    int J = 0; 
    int K = 0; 
    int L = 0; 
    int M = 0; 
    int N = 0; 
    int O = 0; 
    int P = 0; 
    int Q = 0; 
    int R = 0; 
    int S = 0; 
    int T = 0; 
    int U = 0; 
    int V = 0; 
    int W = 0; 
    int X = 0; 
    int Y = 0; 
    int Z = 0; 

    // Now getting the code itself. 
    string toDecode = ""; 
    cout << "Enter code: "; 
    cin >> toDecode; 
    cout << endl; 

    //Now I should be searching the code that was entered to find my various symbols. 
    A = toDecode.find('!'); 
     if (A != -1) { 
     toDecode.insert('!', 1, 'a'); 
     return 0; 
    } 
    B = toDecode.find('^'); 
     if (B != -1) { 
     toDecode.insert('^', 1, 'b'); 
     return 0; 
    } 
    C = toDecode.find('&'); 
    if (C != -1) { 
     toDecode.insert('&', 1, 'c'); 
     return 0; 
    } 
    D = toDecode.find('*'); 
    if (D != -1) { 
     toDecode.insert('*', 1, 'd'); 
     return 0; 
    } 
    E = toDecode.find('@'); 
    if (E != -1) { 
     toDecode.insert('@', 1, 'e'); 
     return 0; 
    } 
    F = toDecode.find('('); 
    if (F != -1) { 
     toDecode.insert('(', 1, 'f'); 
     return 0; 
    } 
    G = toDecode.find(')'); 
    if (G != -1) { 
     toDecode.insert(')', 1, 'g'); 
     return 0; 
    } 
    H = toDecode.find('-'); 
    if (H != -1) { 
     toDecode.insert('-', 1, 'h'); 
     return 0; 
    } 
    I = toDecode.find('#'); 
    if (I != -1) { 
     toDecode.insert('#', 1, 'i'); 
     return 0; 
    } 
    J = toDecode.find('_'); 
    if (J != -1) { 
     toDecode.insert('_', 1, 'j'); 
     return 0; 
    } 
    K = toDecode.find('='); 
    if (K != -1) { 
     toDecode.insert('=', 1, 'k'); 
     return 0; 
    } 
    L = toDecode.find('+'); 
    if (L != -1) { 
     toDecode.insert('+', 1, 'l'); 
     return 0; 
    } 
    M = toDecode.find('['); 
    if (M != -1) { 
     toDecode.insert('[', 1, 'm'); 
     return 0; 
    } 
    N = toDecode.find('{'); 
    if (N != -1) { 
     toDecode.insert('{', 1, 'n'); 
     return 0; 
    } 
    O = toDecode.find('$'); 
    if (O != -1) { 
     toDecode.insert('$', 1, 'o'); 
     return 0; 
    } 
    P = toDecode.find(']'); 
    if (P != -1) { 
     toDecode.insert(']', 1, 'p'); 
     return 0; 
    } 
    Q = toDecode.find('}'); 
    if (Q != -1) { 
     toDecode.insert('}', 1, 'q'); 
     return 0; 
    } 
    R = toDecode.find(';'); 
    if (R != -1) { 
     toDecode.insert(';', 1, 'r'); 
     return 0; 
    } 
    S = toDecode.find(':'); 
    if (S != -1) { 
     toDecode.insert(':', 1, 's'); 
     return 0; 
    } 
    T = toDecode.find(','); 
    if (T != -1) { 
     toDecode.insert(',', 1, 't'); 
     return 0; 
    } 
    U = toDecode.find('%'); 
    if (U != -1) { 
     toDecode.insert('%', 1, 'u'); 
     return 0; 
    } 
    V = toDecode.find('<'); 
    if (V != -1) { 
     toDecode.insert('<', 1, 'v'); 
     return 0; 
    } 
    W = toDecode.find('.'); 
    if (W != -1) { 
     toDecode.insert('.', 1, 'w'); 
     return 0; 
    } 
    X = toDecode.find('>'); 
    if (X != -1) { 
     toDecode.insert('>', 1, 'x'); 
     return 0; 
    } 
    Y = toDecode.find('/'); 
    if (Y != -1) { 
     toDecode.insert('/', 1, 'y'); 
     return 0; 
    } 
    Z = toDecode.find('?'); 
    if (Z != -1) { 
     toDecode.insert('?', 1, 'z'); 
     return 0; 
    } 

    string beenDecoded = ""; 
    /*Now at this point, we need to be able to identify the code when we see it. Let's use the space and type it all out here: 
    '!' ­> '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' 
    */ 
    // Now we have our code. Let's declare a variable for each of those, and set them to equal. 

    // Let's get the message printed: 

    cout << toDecode << endl; 



    return 0; 

} 

Теперь ошибки:

// exception handling support functions 
#include <new> 
#include <stdexcept> 

_STD_BEGIN 
_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xbad_alloc()) 
    { // report a bad_alloc error 

    _THROW_NCEE(_XSTD bad_alloc, _EMPTY_ARGUMENT); 

    } 

_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xinvalid_argument(_In_z_ const char *_Message)) 
    { // report an invalid_argument error 
    _THROW_NCEE(invalid_argument, _Message); 
    } 

_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xlength_error(_In_z_ const char *_Message)) 
    { // report a length_error 
    _THROW_NCEE(length_error, _Message); 
    } 

_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xout_of_range(_In_z_ const char *_Message)) 
    { // report an out_of_range error 
    _THROW_NCEE(out_of_range, _Message); 
    } 

_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xoverflow_error(_In_z_ const char *_Message)) 
    { // report an overflow error 
    _THROW_NCEE(overflow_error, _Message); 
    } 

_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xruntime_error(_In_z_ const char *_Message)) 
    { // report a runtime_error 
    _THROW_NCEE(runtime_error, _Message); 
    } 
_STD_END 

#include <functional> 

_STD_BEGIN 
_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL _Xbad_function_call()) 
    { // report a bad_function_call error 
    _THROW_NCEE(bad_function_call, _EMPTY_ARGUMENT); 
    } 
_STD_END 

#if _HAS_EXCEPTIONS 
#include <regex> 

_STD_BEGIN 
_CRTIMP2_PURE _NO_RETURN(__CLRCALL_PURE_OR_CDECL    _Xregex_error(regex_constants::error_type _Code)) 
    { // report a regex_error 
    _THROW_NCEE(regex_error, _Code); 
    } 
_STD_END 
#endif /* _HAS_EXCEPTIONS */ 

Любая помощь приветствуется!

ответ

1

Весь ваш код выглядит так, будто вы хотите, чтобы что-то случилось, когда вы вызываете функцию insert(), может быть замена символа другим !!!?

Как справедливо упомянул Джон, ни одна из функций insert() не принимает первый параметр в качестве символа, они являются позицией (int или итераторами), в которую вы хотите вставить символ или строку. Все ваши вызовы insert() принимают первый параметр как символ, который дает значение ascii для позиционирования параметра функции insert(), поэтому вы получаете ошибку диапазона.

См синтаксис вставки() здесь string::insert()

string& insert (size_t pos, const string& str); 
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen); 
string& insert (size_t pos, const char* s); 
string& insert (size_t pos, const char* s, size_t n); fill (5) string& insert (size_t pos, size_t n, char c); 
void insert (iterator p, size_t n, char c); 
insert (iterator p, char c); 
void insert (iterator p, InputIterator first, InputIterator last); 

Как я уже говорил ранее, это выглядит как вставка() не функция, которую вы ожидаете, чтобы быть там для вашей цели. Вы ищете замену() символа. Затем используйте,

string& replace (size_t pos, size_t len, size_t n, char c); 

Опять же, эта функция нуждается в позиции в качестве первого параметра. Нечто подобное,

A = toDecode.find('!'); 
     if (A != -1) { 
     toDecode.replace(A, 1,1,'a'); 
     return 0; 
    } 

выше заменить (A, 1,1, 'а') вызов функции заменит первое вхождение '!' символ в строке с 'a'.

Помните, что в функции replace() первый параметр является позицией, если это превышает длину строки, вы получите out_of_range. Второй параметр - количество символов для замены, третье - количество раз, чтобы скопировать символ, а четвертый - символ, который вы хотите поместить в строку.

Update # 1: Посмотрев в свой код немного дальше, что я понимаю, вы на самом деле пытаются заменить «^ & * @() - # _ = + [{$]} ;: ,% <.> /? " символы с символами «abcdefghijklmnopqrstuvwxyz». Ваше «возвращение 0» при каждом условии if все равно испортит это. Я не знаю, почему вы так писали. Тем не менее, в целом, программа может быть простой, например,

#include <string> 
#include <iostream> 
#include <cstddef> 
using namespace std; 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    string actual("abcdefghijklmnopqrstuvwxyz"); 
    string codes ("!^&*@()-#_=+[{$]};:,%<.>/?"); 
    string toDecode =""; 
    cout << "Enter code:";   // get the string to decode 
    cin >> toDecode; 
    cout <<endl; 
    // find the code chars in the entered string 
    size_t found = toDecode.find_first_of(codes); 
    // loop through all the found code characters 
    while(found!=std::string::npos) 
    { 
     // get the position of the found code character in string "codes" 
     // the same position character in string actual is the decoded char 
     size_t cpos=codes.find(toDecode[found]); 
     // assign the decoded char to the code char. Eg: '!'='a' 
     toDecode[found]=actual[cpos]; 
     // Look for the next code character 
     found = toDecode.find_first_of(codes); 
    } 
    cout << toDecode; 
    return 0; 
} 
+0

Отлично! Это решило ошибки.Теперь я выполняю код, и как только я ввожу то, что хочу перевести, он работает без ошибок, но он просто выходит, ничего не отображая. @Naren Neelamegam Вам нужно, чтобы я опубликовал измененный код? – Danny

+0

«return 0» при каждом условии if заставляет вашу программу выйти после замены символа. Обновлен ответ простым способом. Пожалуйста, проверьте. Кроме того, обратитесь к ссылкам на C++, чтобы лучше понять, как их эффективно использовать. –

+0

OH. Спасибо, я думаю, что сейчас работает! – Danny

0

Нет std :: string insert() принимает параметры char, int, char, поэтому ваши символы повышаются до ints, а так как ваша строка пуста - возможно, вы подразумеваете замену вместо вставки?

Я предполагаю, что это заканчивается вызовом insert (size_t pos, size_t n, char c);. Еще один намек на то, что вам нужна вставка str = str.insert(...);

+0

Можете ли вы привести пример «принимать параметры char, int, char», я не уверен, что вы говорите. – Danny

+0

Вы вызываете 'toDecode.insert ('!', 1, 'a');' который не делает то, что вы ожидаете. Он пытается вставить 1 'a' в позицию 33 строки (потому что '!' Является десятичной цифрой 33). Строка не имеет позиции 33. – John3136

Смежные вопросы