如何转换? toString()的C字符串格式

时间:2016-02-23 05:02:02

标签: c++ c-strings

我需要一个toString()的c-string格式,但是如何转换呢?这是功能:

string toString(){
    string tmp;

    char buf[80];
    if (*d != 1)
        sprintf_s(buf, "%d/%d", *n, *d);
    else sprintf_s(buf, "%d", *n);
    tmp = string(buf);

    return tmp;
}

1 个答案:

答案 0 :(得分:1)

  

需要toString()

的c-string格式

如果您只需要转换toString()的输出,则可以使用

const char* s = toString().c_str();

您的函数当前正在返回string(我猜你的代码有using namespace std),这意味着 C ++字符串对象

如果你不是绝对需要C字符串,我建议使用C ++字符串,因为它们更新,更容易使用。但是,如果由于 代码中其他地方的原因需要C字符串,那么您的函数应该看起来像

char* toString() {
    // formatting your output
}

因为所有C字符串都是'\0'的空终止(char)数组,并且数组等同于指向第一个元素的指针,所以char*来自#include <sstream>

在任何一种情况下,C ++ stringstreams都会使输出格式更加直观。您将需要c_str(),然后一些谷歌搜索将引导您朝着正确的方向。如果您需要C字符串,此解决方案可以工作,因为C ++字符串有一个名为#include <string> #include <sstream> using namespace std; char* toString() { stringstream ss; // these are so useful! if (*d != 1) { // this probably isn't the exact formatting you are looking for, // but stringstreams can certainly do it if you research a bit! ss << *n << *d; } else { ss << *n; } string output = ss.str(); return output.c_str(); } 的方法,它将C ++字符串转换为C字符串(以空字符结尾的字符数组):

/* Send Confirmation Email with Google Forms */
function Initialize() {
  var triggers = ScriptApp.getProjectTriggers();
  for (var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }
  ScriptApp.newTrigger("SendConfirmationMail")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onFormSubmit()
  .create();
}


function SendConfirmationMail(e) {
  try {
    var ss, cc, sendername, subject, columns;
    var header, message, value, textbody, sender, itemID, url;

// This is your email address and you will be in the CC
cc = "name@email.com";

// This will show up as the sender's name
sendername = "name to be displayed as sender";

// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Choose an approppiate subject";

// This is the body of the auto-reply
message = "";

ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];

// This is the submitter's email address
sender = e.namedValues["Username"].toString();

// Only include form values that are not blank
for ( var keys in columns ) {
  var key = columns[keys];
//Use this to look for a particular named key
  if ( e.namedValues[key] ) {
    if ( key == "Username" ) {
      header = "The user " + e.namedValues[key] + " has submitted the form, please review the following information.<br />";
    } else {
        message += key + ' ::<br /> '+ e.namedValues[key] + "<br />"; 
      }
    }
  }
}

textbody = header + message;
textbody = textbody.replace("<br>", "\n");

Logger.log("Sending email");
GmailApp.sendEmail(cc, subject, textbody, 
                   {cc: cc, name: sendername, htmlBody: textbody});



} catch (e) {
    Logger.log(e.toString());
  }
}