Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

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 4 days ago 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 4 days ago by avibootz
...