这个问题已得到解答。与格式化程序无关,而是我在复制到新缓冲区时的白痴行为。
<小时/>我希望这是一个简单的答案。我有一个snprintf()
声明如下:
snprintf(buffer, sizeof(buffer), "%03d", 0U);
我在期待buffer
持有000
但由于某种原因它只包含 00
。假设缓冲区足够大,足以容纳我想要的内容。我是不是很傻?
编辑:
请参阅下面的完整代码和上下文。我之前试图简化它,因为我认为所有这些上下文都是不必要的。问题仍然存在,使用 %04u
给我000
在第一个 CSV 行中。 %03u
只给我00
.
uint16_t CSVGenerator::write_csv_data(TestRecord* record)
{
// Define the templates.
const char *row_template = "%04u,%6.3E,%6.3E,%6.3E,%6.3E,%6.3E\n";
char csv_row_buffer[CSV_ROW_BUFFER_SIZE];
// Add the data.
uint16_t row_count = 0U;
for (uint16_t reading = 0U; reading < MEASURE_READING_COUNT; ++reading)
{
// Parse the row.
snprintf(csv_row_buffer, sizeof(csv_row_buffer), row_template,
// Test ID
MEASURE_PERIOD_SECS * reading,
// Impedances Z1-Z5.
record->measurements[reading][0U],
record->measurements[reading][1U],
record->measurements[reading][2U],
record->measurements[reading][3U],
record->measurements[reading][4U]);
// Add it to the main buffer, excluding the terminator.
strncpy((m_csv_data_buffer + (reading * CSV_ROW_BUFFER_SIZE) - 1U),
csv_row_buffer, (sizeof(csv_row_buffer) - 1U));
// Increment the row count.
++row_count;
} // for : each reading.
return row_count;
}
最佳答案
如何检查它是否只包含“000”?如果您从 (m_csv_data_buffer + (reading * CSV_ROW_BUFFER_SIZE))
读取它,您实际上会丢失第一个字节,因为您已将其复制到 (m_csv_data_buffer + (reading * CSV_ROW_BUFFER_SIZE) - 1U)
在您的代码中。
关于在C++中将0复制为000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397029/