alexz
alexz

Reputation: 23

Lining up columns in C++

I am trying to line up columns using the standard <iostream> library and nothing else (so I can't use std::setw, this is for a school exercise).

This is currently my code:

cout << endl;
cout << number_1 << endl;
cout << number_2 << " x" << endl;
cout << "--" << endl;
cout << number_3 << endl;
cout << number_4 << " +" << endl;
cout << "---" << endl;
cout << number_5 << endl; 

It outputs things like this:

35
67 x
--
245
2100 +
---
2345

As you can see, the 245 and 2100 do not line up correctly. The 245 can be a 2-digit number, too (for eg: 45).

Is there any way I can line it up for those possibilities like this, using only the <iostream> library?

  35
  67 x
  --
 245
2100 +
 ---
2345

Upvotes: 0

Views: 157

Answers (1)

sandes
sandes

Reputation: 2267

set max width and align right

cout.width(4); cout << right << "245"<< endl;
cout.width(4); cout << right << "2100" << endl;

But...the solution expected by your teacher is this:

string cout_width(int w, string s){
    
    int len = s.length();
    while(len++ < w)
        s.insert(0, " ");

    return s;
}

int main(int argc, char *argv[]) {
    
    int width = 4;
    
    cout << cout_width(width, "245") << endl;
    cout << cout_width(width, "2100") << endl;
    
    return 0;
}

Upvotes: 3

Related Questions