簡體   English   中英

將字符緩沖區轉換為整數(arduino)

[英]Converting character buffer to an integer (arduino)

解決了:

您可以使用以下方式更改char緩沖區:

char *arg;
arg = SCmd.next();
int i;
sscanf(arg, "%d", &i);
Serial.print("String value "); 
Serial.println(arg); 

Serial.print("Integer value "); 
Serial.println(i); 



問題:

我似乎無法弄清楚如何將char緩沖區的內容從存儲的字符串更改為整數。

例如:

“ 1”應為1,

'121'應該是121

這是我嘗試過的。

void doIt()
{
  char *arg;
  arg = SCmd.next();    // Get the next argument from the SerialCommand object buffer

  if (arg != NULL)      // As long as it existed, do it
  {
    int argInted = (int)arg; // Cast char arg* -> int argInted.

    Serial.print("String value "); 
    Serial.println(arg); 

    Serial.print("Integer value "); 
    Serial.println(argInted); // Print this new found integer.
  } 
  else {
    Serial.println("Fix your arguements"); 
  }
}

這就是我得到的,每次評估為371。 我在指針緩沖區中存儲了不同的東西,關於如何轉換的任何想法?

Arduino Ready
> INPUT 1
String value 1
Integer value 371
> INPUT 2
String value 2
Integer value 371
> INPUT WHATSthisDO
String value WHATSthisDO
Integer value 371

要將char*轉換為int使用atoi()函數。 http://www.cplusplus.com/reference/cstdlib/atoi/

引用WhozCraig:這不是將char *轉換為int的方式

一個簡單的強制轉換不起作用,因為char是1個字節,而int是4個字節,因此剩余的3個字節可以包含任何導致無法預料的結果的垃圾:

char s[1] = {'2'};

cout << s << endl;
cout << (int)s << endl;
cout << atoi(s) << endl;

導致我的機器上

2
-5760069
2

暫無
暫無

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

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