Formatting C++ console output

后端 未结 4 1737
孤城傲影
孤城傲影 2020-12-17 00:41

I\'ve been trying to format the output to the console for the longest time and nothing is really happening. I\'ve been trying to use as much of iomanip as I can

4条回答
  •  旧巷少年郎
    2020-12-17 01:09

    Boost has a format library that allows you to easily format the ourput like the old C printf() but with type safety of C++.

    Remember that the old C printf() allowed you to specify a field width. This space fills the field if the output is undersized (note it does not cope with over-sized fields).

    #include 
    #include 
    #include 
    
    struct X
    {  // this structure reverse engineered from
       // example provided by 'Mikael Jansson' in order to make this a running example
    
        char*       name;
        double      mean;
        int         sample_count;
    };
    int main()
    {
        X   stats[] = {{"Plop",5.6,2}};
    
        // nonsense output, just to exemplify
    
        // stdio version
        fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n",
                stats, stats->name, stats->mean, stats->sample_count);
    
        // iostream
        std::cerr << "at " << (void*)stats << "/" << stats->name
                  << ": mean value " << std::fixed << std::setprecision(3) << stats->mean
                  << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count
                  << " samples\n";
    
        // iostream with boost::format
        std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n")
                    % stats % stats->name % stats->mean % stats->sample_count;
    }
    

提交回复
热议问题