没有正确处理c++字符

C++ Characters not being handled properly

本文关键字:字符 c++ 正确处理      更新时间:2023-10-16

我已经编写了一个基本的加密程序,它从用户的加密文本中获取输入,通常以Unicode字符的形式。但是当我这样做时:

cout << "Your decrypted string is : " << decryptstring(text, key) << endl;

它给了我错误的答案,并得到完全错误的字符代码,如è将是-118

但是当我这样做的时候:

cout << "Your decrypted string is : " << decryptstring("è", key) << endl;

它工作无缝!

如何解决这个问题?如果你需要看我的其他代码,只要问。由于

我从getline(cin, text);得到文本

decryptstring功能:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string decryptstring(string text, string key)
{
    //Declare variables
    int i = 1;
    int result;
    int tmp;
    int tmp2;

    vector < char > arr;

    //Start decryption
    while(i <= text.length())
    {
        /*
        Get letter from the string and get letter from key
        and use Vigenere cipher to decrypt the data.
        */
        tmp  = text[i - 1];
        tmp2 = key[i - 1];
        cout << tmp << endl;
        //Get encrypted value
        result = tmp - tmp2;
        //Change it into readable stuff
        arr.push_back(result);
        //Increment i
        i++;
    }
    string str(arr.begin(), arr.end());
    return str;
}

您需要使用宽字符作为unicode。

decryptstring也是如此:

std::wstring decryptstring(const std::wstring& text, const std::wstring& key) {
   // Do stuff
   return text;
}
然后

std::wcout << L"Your decrypted string is : " << decryptstring(text, key) < std::endl;
std::wcout << L"Your decrypted string is : " << decryptstring(L"è", key) << std::endl;

,

std::wstring text; // is declared before use