Search code examples
carraysstringavruart

Stop string array


How to stop sting array. If I set maximum 40 char that can be put, but I dont want to fill the whole string with 40 char. Here are my code for write char at string array.

int main(void)
 {

    char data[1][40];   
    int i1 = 0;
    int i2 = 0;
        serial_init();

        while (1)
    {

        for (i1=0;i1<1;i1++) 
            { 
               for (i2=0;i2<40;i2++) 
               { 
                  data[i1][i2] = Usart_Receive(); 
               } 
            } 

           for (i1=0;i1<1;i1++) 
           { 
               for (i2=0;i2<40;i2++) 
               { 
                  Usart_Transmit(data[i1][i2]); 
               } 
           }       

      }  
    return 0;   
}

Example If I push if (Usart_Receive() == '.'). It function as stop the string to fill until 40 char. How to do that, I hope someone can help me out here.


Solution

  •     for (i1=0;i1<1;i1++) 
            { 
               for (i2=0;i2<40;i2++) 
               { 
                  data[i1][i2] = Usart_Receive(); 
                  if (data[i1][i2] == '.') {
                      if (i2 < 39) data[i1][i2+1] = '\0';  // null terminate string
                      break
                  }
               } 
            } 
    

    This will stop receive on '.', null terminate the string (if needed), and break out of the loop.