Thread: Text Alignment

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    132

    Text Alignment

    Hi everyone. I am trying to write a program that read the first name of the user, then the second name, and displays each name with its length under it, first aligned to the right, and then, to the left, but I am only being able to accomplish the latter. The code is the following:


    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main (void)
    {
    
        char first[12];
        char last[12];
    
        printf("Type in yout first name:\n");
        scanf("%s", first);
        printf("Type in your last name:\n");
        scanf("%s", last);
    
        printf("%s %s\n", first, last);
                                                       //3rd printf in this line
        printf("%s %s\n", first, last);
        printf("%d\t %d\t\n", strlen(first), strlen(last));
    
        return 0;
    
    }
    How should be the third printf, in order to make the alingment to the right? I tried the following line,

    Code:
    printf("\t%d \t%d\n", strlen(first), strlen(last));
    but the alignment wasn't complete. Thanks in advance!
    Last edited by stdq; 05-02-2011 at 08:06 PM.

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    278
    I think you might have to calculate the number of spaces needed and do it more or less manually.

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Your names will be 11 characters max. If you pad the output to the max length, (both the names printf and the lengths printf), via printf formatting controls, this will be a snap. printf formatting controls can also be used to control justification.
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    132
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GCC & Alignment
    By GReaper in forum Tech Board
    Replies: 2
    Last Post: 02-09-2011, 04:51 AM
  2. Text Alignment
    By LoveTractor in forum C Programming
    Replies: 5
    Last Post: 09-19-2010, 05:36 PM
  3. alignment
    By Frank_Rye in forum C Programming
    Replies: 9
    Last Post: 10-28-2005, 03:18 PM
  4. set() alignment
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 03-14-2002, 04:20 AM
  5. Alignment
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-18-2001, 05:07 PM