【问题标题】:How do you insert a global variable into the middle of a snprinf statement?如何将全局变量插入到 snprinf 语句的中间?
【发布时间】:2021-02-01 00:26:55
【问题描述】:

我有一个全局变量

int CYCLE0;

我想插入一个很长的 snprintf 语句的中间。

snprintf(temp, 400,

           "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>ESP32 Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h2>Turn on</h2> \n\
    <p>cycled "CYCLE0" times</p> \n\"
);

收到错误:

unable to find string literal operator 'operator""CYCLE0' with 'const char [1118]', 'unsigned int' arguments

如何在 snprintf 语句中间插入一个整数变量?

【问题讨论】:

    标签: c arduino printf string-literals


    【解决方案1】:

    这是snprintf 的简单应用。但是,与往常一样,您必须使用 % 说明符来插入某些内容。试试这个:

    snprintf(temp, 400,
        "<html><head>"
        "<meta http-equiv='refresh' content='5'/>"
        "<title>ESP32 Demo</title>"
        "<style>"
        "body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }"
        "</style></head>"
        "<body>"
        "<h2>Turn on</h2>\n"
        "<p>cycled %d times</p>\n",
                  CYCLE0);
    

    我使用字符串常量连接将长字符串拆分为多行,因为我认为这比您在问题中使用的反斜杠延续更方便且更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多