C++字符串问题

标签 c++ c string include

我正在使用 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 类应该被认为是损坏的(根据我的测试,IDE 的版本为 1.6.5,并且可能是 1.0.6 之后的任何版本)。因此,你不能使用

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

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

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

最后,串行类不知道什么是 std::string是,所以如果使用它们,请给它 std::string.c_str()相反

背景

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

我遇到了同样的问题,发现有人创建了 STL for the arduino 的版本(为此向 Andy Brown 表示支持)这是 SGI STL 的精简版。它为arduino提供std::string、std::vector和大量的STL。

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

使用库

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

安装

只需将库提取到(假设您使用的是标准 Arduino IDE)hardware\tools\avr\avr\include文件夹,一切顺利。

使用它

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

首先,您需要包含标题 iterator 之前来自此 STL 的任何库 - 以及在您引用 STL 的每个文件中。

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

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

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

错误

自从 Andy 发布库后,出现了两个错误(我知道)。

第一个Andy自己在博文中进行了整改和解释:

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 中存在一个与 vector 类有关的错误,编译器会提示使用 _M_deallocate。没有前置 this-> ,如果你在 vector 类中搜索它们,你可以修复它

为了您的方便

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

最后

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

如果您在旁注 #include<string>在 header 中,您不需要将其包含在相关的 .cpp 文件中

关于C++字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071453/

相关文章:

c - 访问函数中的双指针结构

c - 与 OpenSSL 的链接错误

java - 使用正则表达式将句子拆分为标记,去除所有必要的标点符号,不包括属于单词一部分的标点符号

java - 是否有更有效的方法来迭代字符串直到到达某个字符?

C# 将字符的 x 次出现附加到字符串

c++ - 在条件中使用 boost::tribool 时是编译器错误还是我的错误?

android - 在 JNI 中使用像素数据创建新的位图?

c++ - 什么更早执行,return 或++?

java - C++ 和 Java 程序之间的交互/通信

c - 如何按顺序将元素从一个链表移动到另一个链表