我打算创建一个简单的函数,它将一个字符串作为其输入,并输出ASCII中该字符串的等效值。 Plz帮助..
void cls(){
system("cls");
}
void getAscii(){
cls();
text(4);
char a[94]={' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',"'\'",']','^','_','`','a','b',
'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] + 32);
printf("%d", &xa);
}
}
}
printf("\n");
}
}
}
答案 0 :(得分:3)
char
只是一个字节的数字。当它代表一个ascii字符时,它实际上只是它的数字。例如,当您说char x = 'A'
时,您基本上是在说char x = 65
。内存中代表x
的一个字节确实存储了数字65
。如果您执行x+1
,则会获得66
或'B'
,具体取决于您的打印方式。当你告诉它打印一个字符时,它会查找ascii表并打印字符。如果您告诉它打印小数,它将打印65
。例如:
char x = 'A';
printf("%d", x);
这将打印65
。您不需要转换表来查找ascii值。
不需要ascii数组和代码中的其他循环。
此
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] + 32);
printf("%d", &xa);
}
}
}
可以简化为
for(i = 0; i < strlen(x); i++) {
printf("%d", x[i]);
}
答案 1 :(得分:1)
您的代码中存在一些错误:
更正的代码是:
#include<stdio.h>
#include<process.h>
#include<string.h>
void cls(){
system("cls");
}
void Ascii(){
cls();
// text(4); //如果它有用的话,取消注释
char a[95]={' ','!','"','#','$','%','&',' ','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b',
'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int j = 0;
for(j = 0; j < 94; j++){
if(x[i] == a[j]){
int xa = (a[j] );
printf("%d ", xa);
}
}
}
printf("\n");
}
}
}
虽然你不需要这个。
试试这个:
void cls(){
system("cls");
}
void Ascii(){
cls();
while(1){
char x[5000], *exitMsg = "quit";
gets(x);
if(strcmp(x, exitMsg) == 0){
break;
}else{
int i = 0;
for(i = 0; i < strlen(x); i++){
int xa = (x[i] );
printf("%d ", xa);
}
}
printf("\n");
}
}