How to format a string using fixed-width fields in C++

2 Answers

0 votes
#include <iostream>
#include <iomanip>

int main()
{
    // Print a table using fixed-width columns

    std::cout << std::left;  // Left-align text

    // Column headers
    std::cout << std::setw(15) << "Name"
              << std::setw(10) << "Age"
              << std::setw(12) << "Salary"
              << '\n';

    // Separator line
    std::cout << std::string(37, '-') << '\n';

    // Data rows
    std::cout << std::setw(15) << "Orion"
              << std::setw(10) << 30
              << std::setw(12) << 75000
              << '\n';

    std::cout << std::setw(15) << "Neo"
              << std::setw(10) << 42
              << std::setw(12) << 92000
              << '\n';
}


/*
run:

Name           Age       Salary      
-------------------------------------
Orion          30        75000       
Neo            42        92000      

*/

 



answered Oct 17 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

// Returns a fixed-width formatted record
std::string formatRecord(const std::string& name,
                         int age,
                         double salary)
{
    std::ostringstream oss;

    // Format fields with fixed widths
    oss << std::left
        << std::setw(15) << name
        << std::setw(10) << age
        << std::setw(12) << salary;

    return oss.str();
}

int main()
{
    std::string result = formatRecord("Atlas ", 30, 95000.0);

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



/*
run:

Atlas          30        95000        

*/

 



answered Oct 17 by avibootz
...