代码之家  ›  专栏  ›  技术社区  ›  Jamescun

向字符串添加字符

  •  2
  • Jamescun  · 技术社区  · 16 年前

    我正在尝试用我的Arduino构建一个非常基本的串行shell。

    我可以使用serial.read()从设备获取输出,并可以获取它输出的字符,但我不知道如何将该字符添加到更长的字符中以形成完整的命令。

    我试过合乎逻辑的方法但没用:

    char Command[];
    
    void loop(){
      if(Serial.available() > 0){
        int clinput = Serial.read();
        Command = Command + char(clinput);
    }
    

    有人能帮忙吗?谢谢您。

    6 回复  |  直到 16 年前
        1
  •  0
  •   Tuomas Pelkonen    16 年前

    如果可以,请使用STD::字符串。如果你不能:

    snprintf(Command, sizeof(Command), "%s%c", Command, clinput);
    

    或者(记住检查命令不会增长太多…)

    size_t len = strlen(Command);
    Command[len] = clinput;
    Command[len + 1] = '\0';
    
        2
  •  3
  •   Curd    16 年前

    你必须一个字符一个字符地写进一个数组。 例如:

    #define MAX_COMMAND_LENGTH 20
    
    char Command[MAX_COMMAND_LENGTH];
    int commandLength;    
    
    void loop(){
      if(Serial.available() > 0){
        int clinput = Serial.read();
        if (commandLength < MAX_COMMAND_LENGTH) {
          Command[commandLength++] = (char)clinput;
        }
    }
    

    顺便说一句:这还没有完成。例如,commandLength必须用0初始化。

        3
  •  1
  •   John Knoeller    16 年前

    你需要在 command 保持最长命令 然后把字符写进去。当你没有角色时, 空值终止命令,然后返回。

    char Command[MAX_COMMAND_CHARS];
    
    void loop() {
      int ix = 0; 
      // uncomment this to append to the Command buffer
      //ix = strlen(Command);
    
      while(ix < MAX_COMMAND_CHARS-1 && Serial.available() > 0) {
         Command[ix] = Serial.read();
         ++ix;
      }
    
      Command[ix] = 0; // null terminate the command
    }
    
        4
  •  0
  •   Michael Aaron Safyan    16 年前

    使用 std::ostringstream 具有 std::string :

    #include <sstream>
    #include <string>
    
    std::string loop()
    {
        std::ostringstream oss;
        while ( Serial.available() > 0 ){
            oss << static_cast<char>(Serial.read());
        }
        return oss.str();
    }
    

    还可以用操作符+连接STD::字符串的多个实例。

        5
  •  0
  •   N 1.1    16 年前

    因为它也标记了C,

    char *command = (char *)malloc(sizeof(char) * MAXLENGTH);
    *command = '\0';
    
    void loop(){
      char clinput[2] = {}; //for nullifying the array
      if(Serial.available() > 0){
        clinput[0] = (char)Serial.read();
        strcat(command, clinput);
    }
    
        6
  •  -1
  •   pm100    16 年前
     char command[MAX_COMMAND];
     void loop(){
         char *p = command;
        if(Serial.available() > 0){
          int clinput = Serial.read();
        command[p++] = (char)clinput;
       }
      }