Weekly Quiz number: 30 (2026)

Solve the quiz and collect tokens!

Type your nickname in the field below before submitting your solution. If you select the correct answer and submit it with your nick-name a token will be generated for you. Collect tokens and the corresponding nickname(s). If you get at least 10 of them you might be rewarded ;-)


Coding Quiz: Input/Output Library

The C standard library has a long memory - its I/O functions quietly carry decades of undefined, unspecified, and implementation-defined baggage into your C++ code.

Question 1: What is a potential issue with this logging function?

#include <cstdio>
#include <string>

void log_temperature(const std::string& label, float value)
{
    std::printf("%d degrees - %s\n", value, label.c_str());
}
std::printf does not check argument types at compile time; passing float for %d is undefined behaviour.
No issue - std::printf is a standard function available in C++ and handles the arguments correctly.

Question 2: What is a concern with this file-reading implementation?

#include <cstdio>
#include <stdexcept>

void process_config(const char* filename)
{
    std::FILE* fp = std::fopen(filename, "r");
    if (fp == nullptr)
    {
        throw std::runtime_error { "cannot open file" };
    }
    char buf[256]{};
    std::fgets(buf, static_cast<int>(sizeof(buf)), fp);
    process_line(buf);   // may throw
    std::fclose(fp);
}
If process_line throws an exception, std::fclose is never called and the file handle leaks - FILE* has no RAII-managed destructor.
No concern - the null check on fp ensures the file is always properly opened and closed.

Question 3: Does save_and_verify correctly read back the saved setting?

A developer saves a configuration value to a file and immediately reads it back to confirm the write succeeded. Will verified hold the expected value?

#include <fstream>
#include <iostream>
#include <string>

void save_and_verify(const std::string& setting)
{
    std::fstream cfg { "config.txt", std::ios::in | std::ios::out | std::ios::trunc };

    cfg << setting << '\n' << std::flush;  // flush to ensure data reaches the OS

    std::string verified{};
    std::getline(cfg, verified);           // read back to confirm

    std::cout << "Saved: " << verified << '\n';
}
Yes - std::flush commits the written data to the OS, so std::getline correctly reads back the saved setting.
No - switching from write to read on the same std::fstream without a positioning call between them is undefined behaviour; std::flush is not a positioning operation.

Make sure your nickname contains at least 8 characters and is a unique as possible.




Disclaimer: