I'm having trouble making a function that centers my results. I cannot find much information depicting how this works exactly. I've found small functions but nothing like I'd like to do. My whole idea is make a function so I can use it at anytime to center my string. Somethings not right.

#include <iostream>
#include <string>

using namespace std;

typedef string::size_type size_type;
typedef unsigned int u_int;

/**
 * Count the number of color codes in the specified string.
 * @param s string containing text with mud color codes
 * @return length of the actual text characters in the string
 */
size_type ccStringLen( string const &s )
{
   
	u_int colors_count = 0;
    for( std::string::const_iterator si = s.begin(); si < s.end(); ++si )
        if( '&' == *si )
            ++colors_count;

    return s.size() - colors_count * 2;
}

 
 void center(string const &str)
 {
    int const screen_len = 80;
    int in_len = str.size();

    int pad_left  = (screen_len - in_len)/2;
    int pad_right = screen_len - pad_left - in_len;

    string lpadding = string( " ", pad_left );
	string rpadding = string( " ", pad_right );
	string out_str = lpadding + str + rpadding;
    cout << out_str;
    
}

int main (void)
{
   

    //                               1           2
    //                      12345678901  23456789012345
    string const title = "&wDummy Title&G and some desc&W";


    size_type title_display_len = ccStringLen( title );
    cout << "Title: " << title << "\nTitle Len:" << title_display_len<<endl;
	cout << center (title)<<endl;
    return 0;
}

Recommended Answers

All 2 Replies

cout << center (title)<<endl;

Change for:

center (title);

And dont't use endl when you need a simple new line, use \n instead.

Look at Line 52.

cout << center (title)<<endl;

You are trying to send a void type to an outputstream.

CODE LINE 26 is the proof of that.

void center(string const &str)

Where as actually you donot need the cout statements as the function implicitly uses cout to display a value. which is at line 37

cout << out_str;

So you will just need to call the function but not cout the function:

so replace the line 52 with

center(title);

This is with the Syntax Errors.

I donot know if your function is properly working or not ,

But there are a few things that I am unable to figure out .

f you are trying cout a value at the center of the screen, why do you need a right- padding when you can always use a '\n' or std::endl to get to the next line...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.