【问题标题】:How to store "%d-%d-%d", year, month, date` as a char?如何将“%d-%d-%d”、年、月、日`存储为字符?
【发布时间】:2017-09-24 17:26:52
【问题描述】:

如何将变量存储在char 变量中?

例如printf("date: %d-%d-%d", year, month, date)"date: %d-%d-%d", year, month, date 组件如何存储为字符?

【问题讨论】:

  • 是格式化后的字符串存储还是格式字符串和参数分开存储?
  • 仅格式化字符串
  • 你看过sprintf吗?
  • @RSahu 是这样的:const char* s = std::printf("date: %d-%d-%d", year, month, date);?如果这个问题看起来微不足道,我很抱歉我是 C++ 新手。
  • 您不能将一堆字符存储在单个字符变量中。您需要使用字符串。看看我下面的回答

标签: c++ string char printf std


【解决方案1】:

使用如下所示的字符串流。您不能使用单个字符来存储一堆字符,因为那是您正在尝试做的事情。

std::stringstream ss;
ss<<yourdate<<theday<<themonth<<theyear;
std::string mystring = ss.str();
std::cout<<mystring;

//to convert to a C-string
const char* aschar = mystring.c_str();

【讨论】:

  • 如何将mystring保存为char
  • 可以使用ss&lt;&lt;"date: "&lt;&lt;theday&lt;&lt;"-"&lt;&lt;themonth&lt;&lt;"-"&lt;&lt;theyear; 将其转换为这种格式:"date: %d-%d-%d"?
  • 是 ss
【解决方案2】:

使用std::snprintf。您可以通过首先调用长度为 0 的 snprintf 然后使用适当大小的缓冲区再次调用它来确定需要多大的缓冲区。

#include <iostream>
#include <string>
#include <cstdio>

int main() {
    const char* pattern = "date: %d-%d-%d";
    int year = 2017;
    int month = 4;
    int date = 27;
    int required = snprintf(nullptr, 0, pattern, year, month, date);
    std::string formatted(required + 1, '\0');
    snprintf(&formatted[0], formatted.size(), pattern, year, month, date);
    // Trim off the extra '\0' character that snprintf puts at the end
    formatted.resize(formatted.size() - 1);

    std::cout << formatted << '\n';
}

我使用std::string 来避免可能的资源泄漏,但您可以使用指向newed 数组的原始char* 来做到这一点。

【讨论】:

    【解决方案3】:
    1. 定义一个足以容纳格式化输出的字符串。
    2. 将其用作sprintf 的第一个参数。

    char output[100];
    sprintf(outout, "date: %d-%d-%d", year, month, date);
    

    如果您能够使用 C++11 编译器,请使用更安全的 sprintfsnprintf 版本。

    char output[100];
    snprintf(output, sizeof(output), "date: %d-%d-%d", year, month, date);
    

    snprintf 确保您不会遇到缓冲区溢出错误。

    【讨论】:

    • 如何扩展未知长度的字符串?例如,如果在日期之后包含名字和姓氏?
    • @Dave,在这种情况下使用std::ostringstream 会更好。
    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2021-10-18
    • 2021-04-29
    • 2021-05-16
    相关资源
    最近更新 更多