簡體   English   中英

用Linux進行C ++編程

[英]c++ programming with linux

我收到的浮點值為-157.571 91.223 -165.118 -59.975 0.953 0 0.474 0 0 0.953 0 0.474 0.474 0 5.361 0 0 0.474 0 5.361 ...一個值並將其放在變量中...可以有人幫我...我用過memcpy但沒有用..如果我要復制8字節的值-157.571,其中包括'-'和'等8個值。 ' ....對此有任何解決方案..

如果我理解正確,則您有一個存儲在某種類型的字符串中的值,並且想要從中檢索浮點值。 如果是這種情況,則取決於您使用的語言。 如果使用的是C ++,則應使用std::istringstream執行轉換。 如果您使用的是C(和/或C ++的cstdio系統而不是iostream ),則應使用sscanf 如果您使用的是C#,則應該使用Double.TryParse

假設您的float緩沖區是以下字符串

"-157.571 91.223 -165.118 -59.975 0.953 0 0.474 0 0 0.953 0 0.474 0.474 0 5.361 0 0 0.474 0 5.361"

您最干凈的C ++方法是將其加載到std::istringstream ,然后使用該流提取浮點值。即

std::istringstream str(buffer);

現在您可以使用流中的in運算符提取浮點值,然后重復此操作,直到沒有更多為止(提示:檢查流標志)

  str >> {float}; // then do something with {float}

(可選)您可以將此提取的值推入std::vector以便為字符串提供浮點數。 我沒有寫完整的代碼,只是偽代碼給你一個主意...

您有一個字符串,其中包含多個浮點值,並用空格分隔。

如果可以使用strtof()將它們轉換為float值。

float strtof( const char *nptr, char **endptr);

where nptr is the string that you wish to convert and endptr is a pointer to a char pointer. endptr will contain the pointer to the last character that was converted, so can be used to walk through your string.

例如。

char *rawString;
char **walkPtr;
float convertedValue;

/* do something to collect the next series of floats */

/* and now do the conversions */
*walkPtr = rawString;
while( still_some_string_to_process )
{
    convertedValue = strtof( *walkPtr, walkPtr );

    // increment the pointer to skip over the delimiting space
    *walkPtr++;
}

應該應用適當的錯誤檢查,以確保您不會用盡字符串的末尾等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM