我如何清除阵列

How do i clear the array

我正在尝试编写一个程序,它可以从串行监视器输入中读取一个字符串并将字符的大小计算为输入数据并将输入存储到数组中,但我遇到了一些麻烦,串行监视器将保留最后输入的数据 例如,如果我输入 ABC 它将显示“输入数据的大小 = 3 个字符”然后我再次输入 ABC 它将保留我之前输入的最后一个数据,我已经将它重置为 0 我犯了什么错误?

串行监视器显示:

请输入

输入数据的大小 = 3 个字符

ABC

请输入

请输入

输入数据的大小 = 7 个字符

ABC

ABC

here's my code:

String Msg  ; 
char buf[1200]={0} ;     // this is an array
char input;
int num=0;
void setup() {
  // Initialize serial and wait for port to open:  
  Serial.begin(115200);
  while (!Serial) 
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
   }
void loop() {
  while (Serial.available()) 
  {
    input = (char)Serial.read();
     if(input != '\n' ) 
    { 
      buf[num] = input;  
      Msg+=input;    
      num++;
     }
     else{
      buf[num++] = input;  // last character is newline
      buf[num] = 0;         // string array should be terminated with a zero
      Serial.println("Please input");
      Serial.print("Size of input data =  ");
      Serial.print(Msg.length());
      Serial.print(" characters");
      Serial.println("");
      Serial.println(Msg);
      Serial.println("Please input");
      Serial.println("");
      Serial.println("");
        for(int i=0; i<num ;i++){
        Msg[i]=0;
        buf[i] =0;
        }
        
       
       }
       num=0;
       }
    return;
         }

根据 Arduino 手册,字符串 [] 运算符与 charAt() 的作用相同。 由于还有一个 setCharAt() 函数,我想 []charAt() 是只读的。

手册上没有这么说,但为什么他们会有 setCharAt()

只要给Msg分配一个空字符串就可以清除它。

Msg = "";

你做错了。

Msg is a String type variable, not an array so you can just clear string like below.

Msg="";

Don't use unnecessary for loop to clear a char buf array you can do it in a better way by using the memset function.

memset(buf, 0, sizeof(buf));

最后,取“num=0;”在 else 循环中,这样一旦完成而不是每次 while 循环执行时它都会为零。

所以最终测试的代码将如下所示,

String Msg  ;
char buf[1200] = {0} ;   // this is an array
char input;
int num = 0;
void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}
void loop() {
  while (Serial.available())
  {
    input = (char)Serial.read();
    if (input != '\n' )
    {
      buf[num] = input;
      Msg += input;
      num++;
    }
    else {
      buf[num++] = input;  // last character is newline
      buf[num] = 0;         // string array should be terminated with a zero
      Serial.println("Please input");
      Serial.print("Size of input data =  ");
      Serial.print(Msg.length());
      Serial.print(" characters");
      Serial.println("");
      Serial.println(Msg);
      Serial.println("Please input");
      Serial.println("");
      Serial.println("");
      Msg ="";
      memset(buf, 0, sizeof(buf));
      num = 0;
    }
    
  }
  return;
}