【问题标题】:Arduino code to removing null character from string从字符串中删除空字符的 Arduino 代码
【发布时间】:2023-01-10 01:26:00
【问题描述】:

我正在使用 nodemcu ESP8266 并编写一个程序来将一些值存储到 EEPROM(分配缓冲区地址 115 到 150 以存储 USERNAME)。 但是当我使用从 115 到 150 的 for 循环读取 EEPROM 数据时,当我检查空值时它将返回带有字符串的空字符,然后没有代码工作,并且在互联网上找不到正确的可能解决方案。 enter image description here

//My Code for store username
String consumername = obj [String("USERNAME")] ;
         Serial.println("writing eeprom > Consumer Name:");
          for (int i = 0; i < consumername.length(); ++i) 
              {
             EEPROM.write(115 + i, consumername[i]);
           Serial.print("Wrote: ");
              Serial.println(consumername[i]);
          }
//My Code for reading username
for (int i = 115; i < 150; ++i) 
 {
     ch = char(EEPROM.read(i));
     if(ch!='\0'){
     oname+= char(EEPROM.read(i));
 }
 }
     Serial .print("Name=");
     Serial .println(oname);

【问题讨论】:

  • 什么是obj?请出示minimal reproducible example
  • 写的时候你写的是实际长度,但是读的时候你读的是 [115,150) 个字符,这意味着有取消设置数据 - 如果您希望读取的是剩余数据,则在写入时更改为写入空值。您还可以保留超过 150 的写作可能性。

标签: c++ arduino embedded nodemcu arduino-c++


【解决方案1】:

在我看来,您在写入 EEPROM 时没有包括字符串终止符。将 i &lt; consumername.length() 更改为 i &lt;= consumername.length() 以包含字符串终止符。

for (int i = 0; i <= consumername.length(); ++i) 
{
         EEPROM.write(115 + i, consumername[i]);
       Serial.print("Wrote: ");
          Serial.println(consumername[i]);
}

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2011-03-24
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多