Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place setw() as a variable

Tags:

c++

I have this sample block of code:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main(){
    string blank = " ";
    cout << "Hello" << blank << "47"; 
}

I have a lot of cout's of this type in my original code. I want to be able to change the blank string to setw(2) function without having to replace blank with setw(2) on each and every cout I have in my code. So is there a way to set a cpp function to a variable? So I can call the function by typing the name? for example:

func blank = setw(2);
cout<< "Hello" << blank << "47";
like image 525
Shayan Avatar asked Apr 30 '26 18:04

Shayan


1 Answers

The type of std::setw(x) is unspecified, but you don't need to know it.

You can just use auto:

auto blank = std::setw(2);

As @StoryTeller noted, while this should work on sane implementations, it's not guaranteed to.

A safer option would be to make a class with overloaded <<:

struct blank_t {} blank;

std::ostream &operator<<(std::ostream &s, blank_t)
{
    return s << std::setw(2);
}
like image 97
HolyBlackCat Avatar answered May 03 '26 07:05

HolyBlackCat