Thread: Don't know how to sold this exersise

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    7

    Don't know how to sold this exersise

    Write a program that requests your first name and does the following with it:
    Prints it in a field three characters wider than the name.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main ( void )
    {
    	char name[20];
    	scanf ( "%s", name );
    	printf ( "%s", name );//If my name is 5 characters long field must be 8
    						  //printf ( "%8s", name );
    	return 0;
    }
    But I don't know how long is scanf input ( name ). If I use strlen() function like this int x = strlen ( name ) I can't just write printf ( "%d%s",x, name). Can this exercise be solved?

  2. #2
    Registered User
    Join Date
    Feb 2010
    Posts
    7
    I figure it out, just put *, like this printf ( "%*s", width, name );

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by dontoo View Post
    I figure it out, just put *, like this printf ( "%*s", width, name );
    I'd just put:
    Code:
    printf("%s   ", name);
    But the one who made the assignment should lose his license to teach. I always hate assignments that make no sense or can be fixed in a way that isn't allowed because it's not what they want to teach you on that moment.

    One thing though; you get a buffer overflow if the name is more than 19 characters. You should really add a length specification to the scanf. For fun, type in a hundred A's and see what happens ;-).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Customer Bill problem
    By karipap in forum C Programming
    Replies: 6
    Last Post: 04-05-2009, 09:25 PM
  2. I need to use 0 to quit a program
    By cwest in forum C Programming
    Replies: 2
    Last Post: 12-15-2001, 08:37 AM
  3. Gameł has sold out!
    By Yoshi in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 12-08-2001, 10:10 PM