【问题标题】:Converting character buffer to an integer (arduino)将字符缓冲区转换为整数(arduino)
【发布时间】:2014-07-13 23:26:11
【问题描述】:

已解决:

您可以使用以下方法更改字符缓冲区:

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 的方式。
  • 尝试打印到除了串口之外的stdout,这样可以排除任何连接问题
  • 请不要在您的原始问题中添加“已解决”,而是将其添加为答案。 (也就是说,除非“您的”解决方案是提议的解决方案之一。)

标签: c++ c arduino arduino-uno


【解决方案1】:

要将char* 转换为int,请使用atoi() 函数。 http://www.cplusplus.com/reference/cstdlib/atoi/

【讨论】:

    【解决方案2】:

    引用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      相关资源
      最近更新 更多