Thread: How to center text using printf?

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    9

    How to center text using printf?

    The overall width of the line is 20 characters. How can I center a string using print so that

    title becomes
    space-title-space

    i have something like this so far
    Code:
    fprintf(myfile, "%20s\n",mystring);
    Last edited by oceans; 07-23-2014 at 12:28 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Do a simple calculation. For example, "title" has a length of 5, so there must be 15 spaces. Therefore, to centre the text, you should insert (15 / 2) = 7 spaces (or 8, if you prefer to round up).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> Therefore, to center the text, you should insert (15 / 2) = 7 spaces
    Don't forget that the field-width needs to include the length of the string - since it's in the field.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    #ifdef _WIN32
    #include <Windows.h>
    int GetColumnWidth()
    {
        CONSOLE_SCREEN_BUFFER_INFO info;
        HANDLE out;
        
        if (!(out = GetStdHandle(STD_OUTPUT_HANDLE)) ||
            !GetConsoleScreenBufferInfo(out, &info))
            return 80;
        return info.dwSize.X;
    }//GetColumnWidth
    #else
    int GetColumnWidth() {return 80;}
    #endif
    
    int main()
    {
        const char *s = "Hey, I'm centered!";
    
        const int total_width = GetColumnWidth();
        const int s_width = strlen(s);
        const int field_width = (total_width - s_width) / 2 + s_width;
    
        printf("%*s\n", field_width, s);
    
        return 0;
    }//main
    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 02-12-2012, 12:18 PM
  2. center text
    By Emerald in forum C Programming
    Replies: 4
    Last Post: 09-02-2009, 06:09 AM
  3. how do i center text using iosflags
    By laxman9052 in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2002, 10:35 PM
  4. Center text
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 05-29-2002, 11:18 AM
  5. Center Text
    By Jperensky in forum C Programming
    Replies: 4
    Last Post: 03-31-2002, 07:40 AM