Thursday, December 8, 2016

Getting good at: C | #2 - getchar and putchar

2 - putchar('='); putchar(')');

How's it going bros. The next jacksepticeye here. Today, I'm going to show you how to use getchar() and putchar(). These are self explanitory: getchar receives a character, and putchar prints out a character. 

So to use putchar, type putchar(':'); in your main function. You can replace ':' with any character you want, so long as you keep it inside the single quotes. Your program should look like this:

int main()
{
    putchar(':');
    return 0;
}

This should print a colon on the screen.

In order to use getchar, we have to be familiar with another type of variable: char. (Actually, you can get away with using regular variables, but I don't recommend it.) Char is a variable that can only be used for characters. (You can set char variables to equal numeric values, but it'll be translated to ASCII, which will make it a character.) To use it, type char name = ':';, where 'name' is any name you want, and ':' is the character the 'name' is set to. Like regular variables, we can set char name to nothing, but to use getchar, you have to set char name equal to getchar(). Your program should look something like this:

int main()
{
    char name = getchar();
    return 0;
}

This allows the user to input any character. To output this character, just add printf("%c",name);, where "%c" tells printf() that the integer we're passing through is a character. Your program should look something like this:

int main()
{
    char name = getchar();
    printf("%c",memes);
    return 0;
}

This allows the user to input a character and outputs the same character. You can also use getchar() to pause a program. For example:


int main()
{
    int memes;
    memes = 1337;
    printf("memes = %d\nPress any key to continue.\n",memes);
    getchar();
    return 0;

}

This prompts the user to enter a character, and only after that will the program stop.

NOTE: You don't have to do the challenges below, but you can if you want to.

With this newfound knowledge, write a program that properly utilize both getchar() and putchar().

That's all I have for now. Until then...

No comments:

Post a Comment