實際上,我有一個具有這種型別的字串:
。"1,Hello,E025FFDA,-126.56,52.34,true"
我想用scanf來決議它,將這些值存盤在相應型別的變數中,所以
uint, char[], maybe string here, ufloat ? , float, bool
我使用帶有"%[^',']"格式指定器的scanf,我測驗每個值是否正確,是否在某個范圍內。
以下是我的代碼:
- param是指向字串開頭的指標
- temp2 是一個臨時變數 。
- local_ptr是param的一個副本,用于不修改param 。
- RCV是一個包含我所有引數的結構 。
if((get_param_length(param) ! = 0) && (sscanf(local_ptr, "%[^', '] , & temp2) == 1)
RCV.binarypayload = temp2;
else[/span
error = 1;
你有什么想法來存盤我的值的最佳型別嗎?或者是任何建議?
uj5u.com熱心網友回復:
沒有任何型別可以匹配你的ufloat。所有的浮點型別都是有符號的,所以從你的字串中提取可以這樣做:
可能的輸出:
1 Hello E025FFDA -126.559998 52.340000 1
如果你想從f1中獲得絕對值,只需在sscanf后面加上f1 = fabsf(f1);。
uj5u.com熱心網友回復:
假設"1,Hello,E025FFDA,-126.56,52.34,true"是你要決議的字串,你可以這樣做:
#include <stdio.h>
int main()
{
char string[] = "1,Hello,E025FFDA,-126.56,52.34,true" /span>;
unsigned int i。
char s1[10]; //你可以在這里調整大小并在scanf()中更新它。
char s2[10] 。
float f1, f2;
char s3[10] 。
if (sscanf(string, "%u,%9[^,] ,%9[^,] , %f,%f,%9s", & i, s1, s2, &f1, &f2, s3) ! = 6)
printf("Error parsing
")。)
else
printf("%u, %s, %s, %f, %s", i, s1, s2, f1, f2, s3) 。
}
這將輸出:
1, Hello, E025FFDA, -126.559998, 52.340000, true
如果你想把"true"存盤在一個bool中:
bool b = !strcmp(s3, "true"); /etc false
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/307876.html
標籤:
