pancakes324
pancakes324

Reputation: 11

Getting a "terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): invalid UTF-8 byte at index 0: 0x81"

I'm working on a coding problem on a website and when I compile my code it gives me:

terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): [json.exception.type_error.316] invalid UTF-8 byte at index 0: 0x81 Aborted exit status 134

However, when I compile on Sublime it works just fine with the correct output. Is there something wrong with how I'm using the ASCII values to store into the string variable answer? Here is my code:

string caesarCypherEncryptor(string str, int key) {
    string answer = "";
    for(char letter : str) {
        // if it goes over 'z': get amount pass 'z' and start at 'a'
        if(letter + key > int('z')) {
            // push back char into answer string
            answer += ((letter + key) % int('z') + int('a'));  
            continue;
        }
        // else just add key from current position
        answer += letter + key; 
    }
    return answer;
}

int main() {

    cout << caesarCypherEncryptor("mvklahvjcnbwqvtutmfafkwiuagjkzmzwgf", 7) << endl;

    return 0;
}

Upvotes: 0

Views: 5427

Answers (2)

Ashish Yadav
Ashish Yadav

Reputation: 121

I also tried out this question, probably on the same website as you mentioned. To any one in the future who is faced with this issue, the problem is in the line of comparison:

if(letter + key > int('z'))

In the above line the ascii value will cross a certain limit which JSON excepts as valid characters, if key is greater than 26, and which by the way is also part of useless calculation, because a key > 26, for example say 27 is same as key = 1.

Hence, the first line of the solution should be key = (key % 26).

This prevents the above given JSON Exception error.

Upvotes: 1

Jaspreet Singh
Jaspreet Singh

Reputation: 1

I faced this issue too. This basically happens when we add int to character and final ascii value cross 127. As result, the ascii value rolls over. i.e. 'z' + 7 = 129 - but it rolls over and becomes - 129 - 127 = 2.

Basically you need to use below condition:

if((unsigned int)(letter + key) > 'z')

Please try this out and let me know if this helps.

Upvotes: 0

Related Questions