提问者:小点点

如何在C++中比较字符的ascii值? [已关闭]


嘿,我正在尝试一个问题,在我的解决方案中,当我尝试比较(在if条件中)时,它给了我意想不到的打印。 有谁能告诉我原因吗?

#include<iostream>
#include<vector>

using namespace std;

int main(){
    
    int T;cin>>T;
    while(T--){
        string s; cin>>s;
        
        int flag=0;
        int p;
        int first=(int)s[0];

        for(int i=0;i<s.length();i++){
            p=(int)s[i];

            cout<<"HELL0 "<<(p<first);    //giving me this unexpectd output "HELL0 53667" but expected true here so due to this my if condition is not running
            if(p<first){
                flag=1;
                break;
            }
            
        }
        
        if(flag==1){
            cout<<"no"<<endl;
        }else{
            cout<<"yes"<<endl;
        }
        
    }
    return 0;
}

以下方面的投入:

1
CCECECECCCCCCCCCCESSSSSSSSSS

以下输出:

HELL0 536 HELL0 536 HELL0 552 HELL0 536 HELL0 552 HELL0 536 HELL0 552 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 536 HELL0 552 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 HELL0 664 yes

共1个答案

匿名用户

我认为您混淆了<运算符和<<运算符。 第一个用于较大/较小比较,第二个用于按位移位。

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    unsigned short short1 = 4;
    bitset<16> bitset1{short1};   // the bitset representation of 4
    cout << bitset1 << endl;  // 0b00000000'00000100

    unsigned short short2 = short1 << 1;     // 4 left-shifted by 1 = 8
    bitset<16> bitset2{short2};
    cout << bitset2 << endl;  // 0b00000000'00001000

    unsigned short short3 = short1 << 2;     // 4 left-shifted by 2 = 16
    bitset<16> bitset3{short3};
    cout << bitset3 << endl;  // 0b00000000'00010000
}

这是Microsoft帮助站点的一个示例,说明如何使用移位运算符,如果这是您打算做的。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中|字符|ascii|值|关闭)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?