c++ - 将字符缓冲区转换为整数(arduino)

标签 c++ c arduino arduino-uno

已解决:

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

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); 
<小时/> <小时/> <小时/>

问题:

我似乎不知道如何将字符缓冲区内容从存储的字符串更改为整数。

例如:

“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

最佳答案

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

关于c++ - 将字符缓冲区转换为整数(arduino),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848934/

相关文章:

c++ - 混合 C 和 C++ makefile

c++ - 线程可连接和分离之间的区别?

c++ - 是否可以在 C++ 中有一个指向模板函数的函数指针?

c - 如何提取 GTK 程序的菜单栏

c++ - 有人可以清楚地解释这段代码的作用吗? - OpenGL 和 SDL

c - Arduino 数组定义

python-2.7 - 如何使用带有 I2C 的 Raspberry Pi 从 Arduino 读取数据

c++ - C4533 警告 : why does goto skip variable initialization?

c++ - 在 C++ 中,是否可以消除数组引用和指针之间的歧义?

c - 通过串行端口发送整数并打印到 LCD