在C++中将0复制为000?

标签 c string printf

这个问题已得到解答。与格式化程序无关,而是我在复制到新缓冲区时的白痴行为。

<小时/>

我希望这是一个简单的答案。我有一个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/

相关文章:

c - 了解堆中的内存分配

c# - 当其内容为\0\0\0\0 时如何确定一个空字符串

python - 如何让用户对 raw_input( ) 的响应访问同名字符串?

C 在csv文件中写入1024行后的数据

c - %.#s 在 c 中的 printf 语句中的格式说明符

c - Noob C 帮助 - 在开关/外壳内循环?

c - 使用 CJSON 解析的 JSON 中的第一个数字始终为 0

c - 是什么导致我使用 realloc 时出现未定义的行为

c++ - 类中的字符串//C++

c - 我如何在 C 文件的开头 fprintf 字符串?