[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables
Leslie
leslie.brothers at verizon.net
Tue Feb 21 16:45:20 UTC 2012
re: C for Beginners, Lesson 2
Hi.
Before I get to the homework, a quick question:
I thought I would modify the 'age' program to input a string (name)
instead.
I guessed I should replace 'int age' with 'char name'.
So I wrote this:
/*
name; an example program showing the difference between
puts and printf
*/
#include <stdio.h>
int main()
{
char name;
puts( "Please enter your name: " );
scanf( "%s", &name );
printf( "Hi, %s.\n", name);
return 0;
}
But when I went to compile, as follows, I got the errors below --
although I thought I gave it the right type, namely char.
leslie:~/cprog$ gcc -o name name.c
name.c: In function ‘main’:
name.c:14: warning: format ‘%s’ expects type ‘char *’, but argument 2
has type ‘int’
********************
This is the relevant text from the Lesson:
> /*
> age; an example program showing
> the difference between puts and printf
> */
>
> #include <stdio.h>
>
> int main()
> {
> int age;
>
> puts( "Please enter your age: " );
> scanf( "%d", &age );
> printf( "Wow, you are %d years old.\n", age);
>
> return 0;
> }
>
> The output of this is nicely-formatted:
>
> $ age
> Please enter your age:
> 80
> Wow, you are 80 years old.
>
> There are a number of cool things happening in this tiny program: it asks for
> input, we enter something, and then it uses it correctly in a sentence. The
> scanf function scans and formats input, and printf formats output. %d is a
> placeholder, and it means scan an integer as a signed decimal number. A signed
> integer can be either a negative or positive number; an unsigned integer is
> only positive.
>
> scanf( "%d", &age ); means "read the user input and place that value into the
> variable age." You must use the & symbol in front of your variable or it won't
> work. If you want to jump ahead this is your introduction to using pointers,
> which is pointing to a specific location on memory. Pointers is a weird and
> complicated subject to explain, so for now I'm going to leave it at "don't
> forget the & symbol when you're playing with scanf." (Anyone who wants to
> chime in with their own explanation of pointers is welcome!)
>
> scanf has already assigned the value of the user input to our age variable, so
> all printf has to do is display it.
>
> Some other commonly-used scanf and printf placeholders are:
>
> %f -- float
> %c -- single character
> %s -- character strings
> %i -- signed integer, or hexadecimal when preceded by 0x and octal when
> preceded by 0
>
>
More information about the Courses
mailing list