将字符串转换为ASCII C ++

时间:2018-11-09 07:23:17

标签: visual-c++

我正在尝试让程序读取2个字符串,然后将它们转换为ASCII值并比较2个值。

我不确定如何将字符串更改为ASCII值以使比较功能正常工作。

datatype aaa = A | B
lemma "(a ~= A) --> (a = B)"

1 个答案:

答案 0 :(得分:0)

char ch[50];
std::cout << "Enter a character: ";
std::cin.getline(ch, sizeof(ch));

char ch[50]“字符数组” ,也称为“字符串”

if (ch[50] == cha[50]) { ... }

chch50都有50个元素。索引从零开始,这意味着最后一个有效元素是ch[49]ch[50]是缓冲区溢出,并导致未定义的行为。

您想声明一个字符char ch;并读取该字符。或声明ch[50]并读取字符串,然后对ch[0](这是索引中的第一个元素)进行比较

int main()
{
    char ch;
    char cha;

    std::cout << "Enter one character: ";
    std::cin >> ch;
    std::cout << "ASCII Value of " << ch << " is " << int(ch) << std::endl;

    std::cout << "Enter a character: ";
    std::cin >> cha;
    std::cout << "ASCII Value of " << cha << " is " << int(cha) << std::endl;

    if(ch == cha) 
    {
        std::cout << "ASCII Value of " << cha << " is " << "equal to " << ch;
    }
    else
    {
        std::cout << ch << " is greater than " << cha << std::endl;
        if(ch > cha)
            std::cout << ch << " is greater than " << cha << std::endl;
        else
            std::cout << ch << " is less than " << cha;
    }

    return 0;
}