C++ 使用 Arduino 将字符串转换为 const char* 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11610264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:20:34  来源:igfitidea点击:

convert String to type const char* using Arduino

c++castingarduino

提问by Caustic

I am using the Arduino library. I would like to log some data from a sensor, date-time stamp it and write it to a SD card.

我正在使用 Arduino 库。我想从传感器记录一些数据,为其添加日期时间戳并将其写入 SD 卡。

To build the text file name I have tried

要构建我尝试过的文本文件名

    String dataFileName = String(String(sedClock.getTime().year(),DEC) + 
                         String(sedClock.getTime().month(),DEC) + 
                         String(sedClock.getTime().day(),DEC) + 
                         String(sedClock.getTime().hour(),DEC) + 
                         String(sedClock.getTime().minute(),DEC) + 
                         String(sedClock.getTime().second(),DEC) + '_log.txt');

I would then like to log to that file using

然后我想使用登录到该文件

      pinMode(SD_PIN,OUTPUT);
      dataFile = SD.open(dataFileName,FILE_WRITE);

But I get

但我得到

    no matching function call to SDClass::open(String&, int) 
    candidates are: File SDClass::open(const char*,uint_8)

But it seems that Arduino string doesn't have the equivalent of

但似乎 Arduino 字符串没有相当于

    (const char *) dataFileName.c_str()

So I can't figure out how to do the correct conversion

所以我不知道如何进行正确的转换

Any help would be greatly appreciated.

任何帮助将不胜感激。

回答by Caustic

Thanks for your help. The solution was

谢谢你的帮助。解决办法是

    char __dataFileName[sizeof(dataFileName)];
    dataFileName.toCharArray(__dataFileName, sizeof(__dataFileName));

    pinMode(SD_PIN,OUTPUT);
    dataFile = SD.open(__dataFileName,FILE_WRITE);

回答by ForEveR