08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2 ■ C – The Basics

to assign a value to name. What we can do is use the standard function strcpy (for string copy),

as in:

strcpy(name, "Alice in Wonderland"); // this is valid

But in order to use strcpy (and other string functions), we must precede our program with

the directive:

#include <string.h>

We summarize all of this in Program P2.1.

Program P2.1

#include <stdio.h> // needed for printf

#include <string.h> // needed for strcpy

int main() {

char name[50];

strcpy(name, "Alice in Wonderland");

printf("Hello, %s\n", name);

}

When run, this program will print

Hello, Alice in Wonderland

In Sections 3.4 and 5.9, we will see how to read a string value into a variable.

Joining two strings is an operation we sometimes want to perform. We say we want to

concatenate the two strings. We can do this with the standard string function strcat (string

concatenation). For example, suppose we have:

char name[30] = "Alice";

char last[15] = "Wonderland";

The statement

strcat(name, last);

will add the string in last to the one in name. It is up to us to ensure that name is big enough to

hold the joined strings. The result is that name will now hold AliceWonderland; the value in last

does not change. The following statements will set name to Alice in Wonderland.

strcat(name, " in "); //one space before and after "in"

strcat(name, last);

40

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!