使用 sprintf() 函数后 C 字符字符串不可读

标签 c string printf arduino-uno arduino-ide

在 Arduino Sketch 上,我需要使用 C 字符串而不是 C++ 字符串对象,以最大限度地减少内存使用。这本身就是一个挑战,因为我不熟悉经典 C。

然而不知何故我让它工作(或多或少)但我遇到了问题。这是一个测试草图来解释它:

#define APIKEY "TWITTER_KEY" //  api key ThingSpeak
#define TARGET_IP "184.106.153.149"///         //local  direccion IP o Hosting  ThingSpeak
#define TARGET_PORT "80"          ///  puerto 80
#define ID "WiFi_ID"  //name of wireless access point to connect to   - Red de inhalambrica wifi 
#define PASS "WiFI_Password"  //wifi password                          - Contraseña de Wifi 



#define TWEET "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."


char foo[400]; //contains the tweet request
char bar[20]; //auxiliary
char numberString[3]; //contains numbers


void setup() {

  Serial.begin(9600);

  testMethod();

}


void testMethod(){

   Serial.println(" ");
   Serial.println("testMethod");
   Serial.println(" ");



    strcpy(foo, "api_key=");
    strcat(foo, APIKEY);
    strcat(foo, "&status=");
    strcat(foo, TWEET);

    Serial.println(foo);


  //sprintf(numberString, "%d", strlen(foo)); //converts the integer into a char


  Serial.println(numberString);


     // Create HTTP POST Data  


     strcpy(foo, "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n");
     strcat(foo, "Host: api.thingspeak.com\n");
     strcat(foo, "Connection: close\n");
     strcat(foo, "Content-Type: application/x-www-form-urlencoded\n");
     strcat(foo, "Content-Length: ");
     strcat(foo, numberString);
     strcat(foo, "\n\n");
     strcat(foo, "api_key=");
     strcat(foo, APIKEY);
     strcat(foo, "&status=");
     strcat(foo, TWEET);


    Serial.println(foo);


  }




void loop() {


}

如果我要取消注释行

 //sprintf(numberString, "%d", strlen(foo)); //converts the integer into a char

然后我无法在串行监视器上打印 foo,也无法打印稍后生成的新 foo。如果我硬编码一个整数而不是 strlen() 函数,情况也是如此。

我会将此描述为一种奇怪的行为,但很可能只是我的无知。我阅读了关于 sprintf() 方法的文档,但我还没有看到任何关于这个问题的信息。

任何帮助将不胜感激。 提前致谢!

最佳答案

strlen(foo) 是一个 3 位数字,因此您需要为 numberString 分配 4 个字节以适应这 3 位数字和 NUL 终止符。

关于使用 sprintf() 函数后 C 字符字符串不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47574054/

相关文章:

string - 输入字段中的Grails格式日期

c - 如何在 Ubuntu 中修改 glibc 来改变 printf() 函数的结果

c - 后台程序中的 printf()

c - 如何在C中的数组中输入字符?

c - 需要澄清指针在给定代码段中如何工作

c - 为什么我的 C 程序中出现 ws2_32.dll 的链接器错误?

PHP使用正则表达式将字符串解析为数组

c - 递归二分法程序停止工作

c - 源到源操作

javascript - 将 splice 与字符串数组结合使用