[英]using fscanf(file, %x, x) and converting hex to ints in C
我想使用fscanf來檢查某些內容是否為十六進制數。 例如,我想打電話
if(fscanf(file,"%x", &u))
就像一個人可以用字符串和整數來調用它。 問題是:首先,你應該是什么類型的? 其次,一旦我得到這個十六進制,即如果if語句通過,我怎么能把你轉換成一個整數?
注意:我想要
if(fscanf(file, "%x", &u) == 1)
如果讀入的數字是0x_ _則為true,否則為false。 我努力了
if(fscanf(file, "0x%x", &u) == 1)
但對於十六進制數字,它返回false
從scanf
手冊頁:
x,X匹配可選的帶符號十六進制整數; 下一個指針必須是指向unsigned int的指針。
你不需要做任何事情來將它轉換為整數,這就是scanf
為你做的。
如果您特別想匹配0x___
,請將其放入格式字符串中:
if (fscanf(file, "0x%x", &u) == 1)
我測試的完整代碼:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
unsigned int u;
if (scanf("0x%x", &u) == 1) {
printf("Read hex: %u\n", u);
} else if (scanf("%u", &u) == 1) {
printf("Read decimal: %u\n", u);
}
}
關於@Barmar的討論值得贊揚。
讀取數據並通過sscanf()
或strtol()
以多種方式處理它。
unsigned u;
char buf[27];
if (scanf("%26[xX0-9A-Fa-f]", buf) != 1)
;//handle_bad_input();
else {
char ch;
if (sscanf(buf, "%u%c", &u, &ch) == 1)
printf("decimal found %u", u);
else if (sscanf(buf, "0x%X", &u) == 1)
printf("hexadecimal found 0x%X", u);
else
;//handle_bad_input();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.