繁体   English   中英

使用Arduino和C ++进行字符串操作

[英]String manipulation using Arduino and C++

我试图在C ++中操纵一个字符串。 我正在使用Arduino板,因此我对可以使用的内容有限。 我还在学习C ++(对不起任何愚蠢的问题)

这是我需要做的:我需要每小时发送一英里到7段显示。 所以,如果我有一个像17.812345这样的数字,我需要在7段显示器上显示17.8。 看起来最有效的方法是首先乘以10(这是将小数点右移一个位置),然后将178.12345转换为int(关闭小数点)。 我坚持的部分是如何分解178.在Python中我可以切割字符串,但我找不到任何关于如何在C ++中执行此操作(或者至少,我找不到合适的搜索条件对于)

有4个7段显示器和7段显示控制器。 它的速度可达每小时十分之一英里。 非常感谢您提供的帮助和信息。

将它转换为字符串可能最简单,但只是使用算术来分隔数字,即

float speed = 17.812345;
int display_speed = speed * 10 + 0.5;     // round to nearest 0.1 == 178
int digits[4];
digits[3] = display_speed % 10;           // == 8
digits[2] = (display_speed / 10) % 10;    // == 7
digits[1] = (display_speed / 100) % 10;   // == 1
digits[0] = (display_speed / 1000) % 10;  // == 0

并且,如评论中所指出的,如果您需要每个数字的ASCII值:

char ascii_digits[4];
ascii_digits[0] = digits[0] + '0';
ascii_digits[1] = digits[1] + '0';
ascii_digits[2] = digits[2] + '0';
ascii_digits[3] = digits[3] + '0';

这种方式你可以在没有模数学的C ++中做到(这两种方式对我来说似乎都很好):

#include "math.h"
#include <stdio.h>
#include <iostream.h>

int main( ) {

        float value = 3.1415;
        char buf[16]; 
        value = floor( value * 10.0f ) / 10.0f;
        sprintf( buf, "%0.1f", value );

        std::cout << "Value: " << value << std::endl;

        return 0;
}

如果您真的想将这些东西作为字符串处理,我建议您查看stringstream 它可以像任何其他流一样使用,例如cincout ,除了不是将所有输出发送到控制台,你得到一个实际的string

这将适用于标准C ++。 不太了解Arduino,但一些快速的谷歌搜索表明它不会支持stringstreams。

一个简单的例子:

#include <sstream> // include this for stringstreams
#include <iostream>
#include <string>

using namespace std; // stringstream, like almost everything, is in std

string stringifyFloat(float f) {
  stringstream ss;
  ss.precision(1); // set decimal precision to one digit.
  ss << fixed;     // use fixed rather than scientific notation.
  ss << f;         // read in the value of f
  return ss.str(); // return the string associated with the stream.
}

int main() {
  cout << stringifyFloat(17.812345) << endl; // 17.8
  return 0;
}

你可以使用像toString这样的函数,就像你在Python中那样工作,或者只是使用modulo 10,100,1000等将它作为数字。 我认为将它作为字符串进行操作对您来说可能更容易,但它取决于您。

你也可以使用boost :: lexical_cast ,但在像你这样的嵌入式系统中可能很难获得提升。

一个好主意是为显示器实现一个流。 这样就可以使用C ++流语法,并且应用程序的其余部分将保持通用。

如果您仍想使用std::string ,则可能需要使用反向迭代器。 and work towards the left, one character at a time. 这样,您可以从最右边的数字 ,向左移动,一次一个字符。

如果您可以访问运行时库代码,则可以为显示设置C语言I / O. 这比C ++流更容易实现。 然后,您可以使用fprint,fputs写入显示。 我在这个方法中实现了一个调试端口,其他开发人员更容易使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM