[英]Read Extended ASCII Characters from File and Convert to ASCII Decimal Value
[英]Read several ASCII characters and get the value
有人可以解釋或糾正我的代碼嗎? 我正在嘗試輸入幾個字符並獲得ascii值
例如:輸入:ab; 輸出:9798
這是我的代碼,但最后有一個10
#include <stdio.h>
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
printf("%d",c);
}
return 0;
}
如果查看ASCII表 ,則十進制值為10
是換行符。 換句話說,您將\\n
字符作為輸入的一部分處理。 例如,當用戶復制粘貼多行或按下Enter鍵時,可能會發生這種情況。 如果您不希望這種情況發生,您需要格外小心忽略\\n
。 例如:
#include <stdio.h>
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
if (c == '\n')
break; /* Or perhaps continue? Depends on what you actually want. */
printf("%d",c);
}
return 0;
}
另請注意,不同的系統可能有不同的約定,實際上是換行符。 在UNIX上,它只是\\n
字符,在Windows上,它可能是組合或\\r
和\\n
。 因此,如果您想讓您的程序可移植,則需要將其考慮在內。 您可以自己做,也可以使用其他庫(想到GNU getline )。 您可以在此處閱讀有關換行的更多信息。
您可能希望從輸出中排除一些字符,而不僅僅是'\\ n',在這種情況下,您可以嘗試這樣的事情:
#include <stdio.h>
int isEndingChar(char c) {
char terminators[3] = {'\r','\t','\n'}
int n;
for( n=0; n<3; n++ ) {
if( terminators[i]==c )
return 1;
}
return 0;
}
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
if( isEndingChar( c ) )
break;
printf("%d",c);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.