C++字符串问题

C++ problems with string

我正在使用 cpp 和 h 文件进行一些 arduino 开发,但在使用字符串时遇到了一些麻烦。目前我有

#include <string>

在 cpp 和 h 文件的顶部。当我这样做时,它给了我错误:

string: no such file or directory

如果我进入 h 文件并将其更改为

#include <string.h>

然后它给我错误:

std::string has not been declared

任何时候我使用我使用的字符串:std::string 来声明它。我没有使用 namespace std,在我开始尝试使用 string 之前,这些文件可以很好地协同工作。我是 C/C++ 的新手,所以非常感谢您的帮助。谢谢!

简而言之,有一种方法可以将 std::string 与 Arduino 一起使用。

长话短说: link to the arduino STLv1.1.2

注意

请注意,目前由该 STL 提供的 harrdwareserialstream class 应该被认为是损坏的(根据我的测试,IDE 的 1.6.5 版本,可能是 1.0.6 之后的任何版本).因此,您不能使用

hardwareserialstream << "Hi there person number " << (int)i

等等。它似乎不再工作,因为引用了它将与之交互的串行端口而不是指针 - 简而言之,继续使用

Serial.print("Hi there person number");
Serial.print((int)i);

最后,序列号 classes 不知道什么是 std::string,所以如果使用它们,请给它 std::string.c_str() 而不是

背景

正如 McEricSir 在评论中所说,arduino 确实提供了自己的字符串 class,尽管我发现它存在与内存泄漏相关的问题,最终吃掉了我所有的内存和程序已停止 运行 - 虽然这是在 arduino IDE v 1.0.5 中,但从那时起它可能已被修复。

我遇到了同样的问题,发现有人创建了 STL for the arduino 的一个版本(安迪布朗为此提供支持),它是 SGI STL 的简化版本。它为arduino提供了std::string、std::vector和大量的STL。

虽然使用它时有一些注意事项;如果您的电路板内存很少,您可以使用智能容器和其他高级功能快速填充它。

使用图书馆

要使用该库,您需要阅读这篇文章,不过我会在这里为您总结要点:

安装

只需将库解压缩到(假设您使用的是标准 Arduino IDE)hardware\tools\avr\avr\include 文件夹即可。

使用它

要实际使用新库,您需要包括 2 个额外的东西以及您想要的库。

首先,您需要包含 header iterator BEFORE 来自此 STL 的任何库 - 并且在每个文件中引用 STL .

其次,您还需要包含文件 pnew.cpp 以提供 new 运算符的实现,供 STL 使用。

最后,像往常一样包含任何 header 个文件。

要使用从它们获得的类型,请不要忘记它们的 std:: 命名空间符号。 (std::string 等等)

错误

自从 Andy post编辑了库后,出现了两个错误(我知道)。

第一个安迪自己在博客里整改解释post:

The compiler will spit out a typically cryptic succession of template errors, with the key error being this one:

dependent-name std::basic_string::size_type is parsed as a non-type, but instantiation yields a type c:/program files (x86)/arduino-1.0/ hardware/tools/avr/lib/gcc/../../avr/include/string:1106: note: say typename std::basic_string::size_type if a type is meant

Basically the STL was written a long time ago when C++ compilers were a little more forgiving around dependent types inherited from templates. These days they are rightly more strict and you are forced to explicitly say that you mean a type using the typename keyword.

此外,他还提供了更新版本供您获取。

最后,评论中有关于 IDE 新版本中与向量 class 相关的错误的报告,编译器抱怨 _M_deallocate 的使用没有一个前缀 this->,如果你在向量 class

中搜索它们,你可以修复它

为了您的方便

因为我经常使用它,所以我打包了当前版本,can be found here(这包括我评论过的两个修复)

最后

使用它时,一定要留意你的空闲内存,为此我推荐优秀的 class MemoryFree Library found here

附带说明,如果您 #include<string> 在 header 中,则不需要将其包含在相关的 .cpp 文件中