Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   %d confusion (http://www.programmingforums.org/showthread.php?t=12103)

m0rb1d Dec 4th, 2006 8:39 AM

%d confusion
 
After attempting QBasic, and being deterred whilst getting help here ( not a bad thing, just stating the facts ) I decided to make an attempt at C. Following my same routine, I sought out an online tutorial.

For the record, I got back to college in spring, and would like to be prepared for the programming courses I will inevitably be taking.

Anyway, found one on howstuffworks dot com. It is rather simple to follow, but there is one point, I do not quite understand.

I gather the meaning of %d. It's a placeholder for a variable value. such as

:

int a;
a = 10
    printf("The value of a is %d\n")


This is the same thing as

:

a = 10
  PRINT "The value of a is " ;a

in qbasic. ( helps me to see the difference, sorry )

Well, in one example:

:

#include <stdio.h>

int main()
{
    int a;
    a = 0;
    while (a <= 100)
    {
        printf("%4d degrees F = %4d degrees C\n",
            a, (a - 32) * 5 / 9);
        a = a + 10;
    }
    return 0;
}


they use %4d. Im not quite sure I understand this. They just explain that you use %d to print a variable into a line of text.

So, does %4d express a 4 number INT, or is used because of some other reason they just neglected to leave out of the tutorial?

I also see that the printf line is slightly different than in previous uses.
a, (a - 32) * 5 / 9); is just a continuation of the printf line if I am not mistaken. So, I suppose %4d is used rather than %d because there are commands at the end of the line?

DaWei Dec 4th, 2006 8:45 AM

First of all, a simple visit to the printf documentation would answer your questions. "%d" is one form of one format specifier. The "%" is the clue. "d" indicates an integer, as "s" would indicate a string. There are several others. The things between the "%" and the "d" have various meanings, such as width, precision, and so forth. The first argument is the format string. The following arguments specify the values to be formatted, one for each specifier. These values can be expressions. Again, just man printf, or visit your help file, or Google. It will repay you handsomely.

m0rb1d Dec 4th, 2006 10:29 AM

I am using Bloodshed Dev-C++. Yes, it does have documentation on printf, but nothing that my apparantly not-so-keen eyes could find about %xd.

Arevos Dec 4th, 2006 11:22 AM

Quote:

Originally Posted by m0rb1d (Post 120542)
After attempting QBasic, and being deterred whilst getting help here ( not a bad thing, just stating the facts ) I decided to make an attempt at C.

Slightly off-topic, but if you're coming from QBASIC, then you may find C difficult and unfamiliar. This isn't necessarily a bad thing, as it exposes one to a different way of thinking, but you may find things hard going. I started programming with QBASIC (well, originally Dragon BASIC), and then moved onto C. However, I found it rather hard to grasp at the time, and in retrospect, I would have done better learning something like Python instead.

YMMV, of course. I was rather young when I started, so you may be able to grasp the fundamentals with more ease than I did.

You may also want to look at Ruby; whilst a little more quirky than Python, there are some very unconventional and amusing tutorials around for it. It's also well suited for problems that require an Object Orientated solution, such as an RPG.

m0rb1d Dec 4th, 2006 11:41 AM

Im not really having as much trouble as I thought with C. It's just a matter of recognising what does what in C and comparing it to what does what in BASIC. If I can point out the differences, I can mentally do the work with minimal confusion.

I have had a look at RUBY. I suppose a big part of the problem is, I dont see the point in learning something that is going to be unbeneficial to me. As with BASIC being a rarity, and the way things are done with basic not being used, I have a hard time putting my full attention forth.

DaWei Dec 4th, 2006 12:26 PM

If your compiler's documentation is pitiful, and you're not on a *nix system with man pages, very extensive documentation can be found via Google. cplusplus.com, for instance, says:
:

printf
<stdio.h>       
  cplusplus.com 
int  printf ( const char * format [ , argument , ...] );

Print formatted data to stdout.
  Prints to standard output (stdout) a sequence of arguments formatted as the format argument specifies.

Parameters.

format
    String that contains the text to be printed.
    Optionally it can contain format tags that are substituted by the values specified in subsequent argument(s) and formatted as requested.
    The number of format tags must correspond to the number of additional arguments that follows.
    The format tags follow this prototype:
   
    %[flags][width][.precision][modifiers]type
   
      where type is the most significant and defines how the value will be printed:
    type        Output        Example
    c
            Character        a
    d or i
            Signed decimal integer        392
    e
            Scientific notation (mantise/exponent) using e character        3.9265e2
    E
            Scientific notation (mantise/exponent) using E character        3.9265E2
    f
            Decimal floating point        392.65
    g
            Use shorter %e or %f        392.65
    G
            Use shorter %E or %f        392.65
    o
            Signed octal        610
    s
            String of characters        sample
    u
            Unsigned decimal integer        7235
    x
            Unsigned hexadecimal integer        7fa
    X
            Unsigned hexadecimal integer (capital letters)        7FA
    p
            Address pointed by the argument        B800:0000
    n
            Nothing printed. The argument must be a pointer to integer where the number of characters written so far will be stored.       

      the other flags, width, .precision and modifiers sub-parameters are optional and follow these specifications:
   
    flags
            meaning
    -
            Left align within the given width. (right align is the default).
    +
            Forces to preceed the result with a sign (+ or -) if signed type. (by default only - (minus) is printed).
    blank
            If the argument is a positive signed value, a blank is inserted before the number.
    #
            Used with o, x or X type the value is preceeded with 0, 0x or 0X respectively if non-zero.
    Used with e, E or f forces the output value to contain a decimal point even if only zeros follow.
    Used with g or G the result is the same as e or E but trailing zeros are not removed.
   
    width
            meaning
    number
            Minimum number of characters to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger.
    0number
            Same as above but filled with 0s instead of blanks.
    *
            The width is not specified in the format string, it is specified by an integer value preceding the argument thas has to be formatted.
   
    .precision
            meaning
    .number
            for d, i, o, u, x, X types: precision specifies the minimum number of decimal digits to be printed. If the value to be printed is shorter than this number the result is padded with blanks. The value is never truncated even if the result is larger.(if nothing specified default is 1).
    for e, E, f types: number of digits to be printed after de decimal point. (if nothing specified default is 6).
    for g, G types : maximum number of significant numbers to be printed.
    for s type: maximum number of characters to be printed. (default is to print until first null character is encountered).
    for c type : (no effect).
   
    modifier
            meaning (affects on how arguments are interpreted by the function)
    h
            argument is interpreted as short int (integer types).
    l
            argument is interpreted as long int (interger types) or double (floating point types).
    L
            argument is interpreted as long double (floating point types).

argument(s)
    Optional parameter(s) that contain the data to be inserted instead of % tags specified in format parameter. There must be the same number of these parameter than the number format tags.

Return Value.
  On success, the total number of characters printed is returned.
  On error, a negative number is returned.

Example.

/* fprintf example: some format examples */
#include <stdio.h>

int main()
{
  printf ("Characters: %c %c \n", 'a', 65);
  printf ("Decimals: %d %ld\n", 1977, 650000);
  printf ("Preceding with blanks: %10d \n", 1977);
  printf ("Preceding with zeros: %010d \n", 1977);
  printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
  printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
  printf ("Width trick: %*d \n", 5, 10);
  printf ("%s \n", "A string");
  return 0;
}


And here is the output:

Characters: a A
Decimals: 1977 650000
Preceding with blanks:      1977
Preceding with zeros: 0000001977
Some different radixes: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick:    10
A string


See also.
  fprintf, scanf


Arevos Dec 4th, 2006 12:36 PM

Quote:

Originally Posted by m0rb1d (Post 120554)
Im not really having as much trouble as I thought with C. It's just a matter of recognising what does what in C and comparing it to what does what in BASIC. If I can point out the differences, I can mentally do the work with minimal confusion.

My aversion to new programmers learning C may just boil down to having attempted to learn it at too early an age, or perhaps I'm just dumb ;)

Incidentally, your approach at learning C - comparing it to a language you already know - is a common and effective way of learning new programming languages. Indeed, the more languages you learn, the more points of reference you have to learn more languages.

Quote:

Originally Posted by m0rb1d (Post 120554)
I have had a look at RUBY. I suppose a big part of the problem is, I dont see the point in learning something that is going to be unbeneficial to me.

I'll have to agree with you there - learning something that isn't beneficial is generally something I try to avoid. However, I've found learning a programming language is almost always beneficial enough to warrant learning; not only do you know a new language to use, it also gives you a different point if view, a different way of approaching a problem.

The larger the viewpoint shift, the harder the programming language is to learn, but the more beneficial the results. Haskell, for instance, is the language I'm currently learning, and it has concepts in it that are almost completely alien to the programming I have done before. It took me a long time to understand monads enough to be confident with their use; they're really unlike anything I had encountered before.

On the other hand, learning C# took hardly any time at all, because it's so similar to C++ and Java, two languages which I already knew very well.

As for learning Ruby, you may want to take a look at Why's (Poignant) Guide to Ruby. It's really unlike any other programming tutorial I read, and rather more amusing. Chapter 6, for instance, revolves around Rabbit objects fighting monsters by use of overloaded mathematical operators and metaprogramming.

Harakim Dec 4th, 2006 2:43 PM

Don't worry. printf is not very intuitive.

Someone correct me as I'm probably wrong, but...

%a.bx

a is the number of characters to the left of the decimal
b is the number to the right and
x is a character representing the data type:
s - string
d/i - integer
ul - unsigned long
etc.

a and b mean different things when you are talking about strings. I'm pretty unclear on this, but I think they are the maximum and minimum number of characters or something like that.

printf("jk %s als%.5fhl;khas %df", a, b, c);
The %s corresponds to 'a'. 'a' will be read as a string and pasted into the original string, replacing %s
The %f corresponds to 'b'. 'b' will be read as a floating point variable and pasted into the original string... It will also be limited to 5 places after the decimal point.
The %d will be turned into the decimal that is stored in 'c'.

There can be pretty much an unlimited number of % arguments in a printf statement, but you need to have a variable (a,b, or c in this case) for each one.


Hopefully, this will help you a little.

Jessehk Dec 4th, 2006 2:52 PM

Aa a former fan, let me say that Ruby is fun. However, with time, I realized that Python is a much better language if you're planning to build anything on a large scale. It's much more readible, and the multitude of different ways to do one thing in Ruby tend to get confusing when reading other code.

When I see code in Ruby, it often seems like a contest of who can fit the most clever code in the smallest number of lines.

Arevos Dec 4th, 2006 3:45 PM

Ruby has its moments. It's class system is more expressive and more elegant than Python's, and, let's face it, fitting the most clever code in the smallest number of lines is pretty fun ;)


All times are GMT -5. The time now is 1:36 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC