2009-12-05 46 views
2

我想操作C++中的字符串。我正在使用Arduino板,所以我只能使用它。我也仍然在学习C++(对不起,对于任何愚蠢的问题)使用Arduino和C++进行字符串操作

这是我需要做的: 我需要发送每小时英里数7段显示。所以如果我有一个数字如17.812345,我需要在7段显示器上显示17.8。什么似乎是最有效的方法是首先乘以10(这是将小数点右移一位),然后将178.12345转换为int(以关闭小数点)。我坚持的部分是如何拆分178.在Python中,我可以切分字符串,但是我找不到任何关于如何在C++中执行此操作的问题(或者至少我找不到要搜索的正确术语)

有四个7段显示器和一个7段显示控制器。它将每小时测量高达十分之一英里。非常感谢您提供给我的帮助和信息。

+0

非常感谢您的信息和帮助。我真的很感激 – Dan 2009-12-05 15:30:49

+0

@丹如果你有一个答案解决了你的Arduino问题,请通过按下绿色的勾号告诉我们哪一个。因此,具有相同Ardunio问题的其他人知道要先尝试什么。 – 2009-12-05 21:20:33

回答

10

它很可能是最容易把它转换为字符串,但只是用算术的数字分开,即

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'; 
+0

当然,如果他真的需要这些数字,那么只需要获取数字的各个元素并获取ASCII码即可。 – imaginaryboy 2009-12-05 07:04:00

4

这一种方法可以做到这一点在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; 
} 
+2

'buf'应该大于4,因为即使“17.8”也没有留下空终止符的空间。 – cobbal 2009-12-05 08:09:07

+0

好点cobbal - 你抓住我试图过度优化,红色手掌。 2^4应该足够:) – 2009-12-05 10:25:12

2

如果你真的想把这些东西当作字符串处理,我会建议你看看stringstream。它可以与任何其他流很相似,如cincout,除了将所有输出发送到控制台之外,您将得到实际的string超出交易。

这将使用标准的C++。对Arduino不太了解,但是一些快速的谷歌搜索表明它不会支持字串流。

一个简单的例子:

#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; 
} 
0

可以使用这样的功能,因为这toString和您的方式工作,从那里,就像你在Python会,或者只是使用模10,100,1000等,以得到它作为数字。我认为把它作为一个字符串来操作对你来说可能更容易,但是它取决于你。

您也可以使用boost::lexical_cast,但在您的嵌入式系统中可能很难提升工作效率。

0

一个好主意是实现显示流。这样可以使用C++流语法,应用程序的其余部分仍然是通用的。 虽然这可能是一个嵌入式系统的矫枉过正。

如果您仍想使用std::string您可能需要使用反向迭代器。这样,您可以从最右边的数字(在字符串中)开始,向左一个字符。

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