How to compare an ASCII value

若如初见. 提交于 2019-12-12 21:35:30

问题


I want to store the ASCII value of a letter into a variable, how can I do this?

for example :

r ASCII variable = 82
main()
{
    character = "character read from a file";
    variable= "r ascii"; //(in this case 82), the problem is that the letter is always        variable.;
    printf( "the value of %c is %d, character, variable)
}

How can I do this?

Also on an extra note, how could I read a .txt file character by character? so It could be saved on the character variable.


回答1:


Just do:

if (r == 82) {
   // provided r is a char or int variable
}

In C, char variables are represented by their ASCII integer value, so, if you have this:

char r;
r = 82;
if (r == 82) {
}

Is the same as:

char r;
r = 'R';
if (r == 'R') { // 'R' value is 82

} 

You can even mix them:

char r;
r = 82;
if (r == 'R') { // will be true

}



回答2:


If you just want to save the ascii value onto an integer variable

just use this

int b;
char c = 'r';
b = (int)c;
printf("%d",b);


来源:https://stackoverflow.com/questions/7465494/how-to-compare-an-ascii-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!