如何清除数组



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

串行监视器显示:

请输入

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

ABC

请输入

请输入

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

ABC

ABC

这是我的代码:

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手册,String[]运算符的作用与charAt()相同。由于还有setCharAt()函数,我假设[]charAt()是只读的。

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

只需给Msg分配一个空字符串即可清除它。

Msg = "";

你做这件事的方式不对。

Msg是一个String类型的变量,而不是数组,所以您可以像下面这样清除字符串。

Msg="";

不要使用不必要的for循环来清除char-buf数组,可以使用memset函数以更好的方式进行清除。

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

最后;num=0"在else循环内部,这样它在完成后将为零,而不是每次执行循环时都为零。

所以最终测试的代码会是这样的,

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

最新更新