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 8 ■ Arrays

Suppose a country’s data are read into the variables country, capital and CAPITAL,

respectively. (Remember that, in C, capital is a different variable from CAPITAL.) When the user

types an answer (answer, say), it must be compared with capital. If we use a straightforward

comparison like

if (strcmp(answer, capital) == 0) ...

to check if answer is the same as capital, then answers such as "Portof Spain,""port of

spain,"" Port ofSpain," and "st georges" would all be considered wrong. If we want these

answers to be correct (and we probably should) we must convert all user answers to a common

format before comparing.

We take the view that as long as all the letters are there, in the correct order, regardless of

case, the answer is considered correct. When the user types an answer, we ignore spaces and

punctuation and convert the letters only to uppercase. This is then compared with CAPITAL. For

example, the answers above would be converted to "PORTOFSPAIN" and "STGEORGES" and would

elicit a "Correct!" response.

In the palindrome program (P8.5), we wrote a function lettersOnlyLower that kept the

letters only from a string and converted them to lowercase. Here, we want the same function but

we convert to uppercase instead. We name the function lettersOnlyUpper. The code is identical

to lettersOnlyLower except that tolower is replaced by toupper. Our test for correctness now

becomes this:

lettersOnlyUpper(answer, ANSWER);

if (strcmp(ANSWER, CAPITAL) == 0) printf("Correct!\n");

All the details are captured in Program P8.7.

Program P8.7

#include <stdio.h>

#include <string.h>

#include <ctype.h>

#include <stdlib.h>

#define MaxLength 50

int main() {

void getString(FILE *, char[]);

void askOneQuestion(char[], char[], char[]);

char EndOfData[] = "*", country[MaxLength+1] ;

char capital[MaxLength+1], CAPITAL[MaxLength+1];

FILE * in = fopen("quizdata.txt", "r");

if (in == NULL){

printf("Cannot find file\n");

exit(1);

}

231

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!