Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Strings.

READTask 2 of 20 · step 2: Working with stringsWorking with strings
Working with strings in practice/05/

snprintf instead of = and strcpy, strcmp instead of ==, strchr and strcspn, <ctype.h> with (unsigned char).

Details & hint

A string is an array, so = and == don't work on it the way they do on numbers. That's what the functions from <string.h> are for.

Assigning: not =, but snprintf

char city[20];
city = "Kaunas";          /* error: you can't assign to an array */
error: assignment to expression with array type

Text has to be copied into an array. The safest way is snprintf: it works like printf, except it writes into an array and never goes past the size you give:

snprintf(city, sizeof city, "%s", "Kaunas");
snprintf(full, sizeof full, "%s %s", name, surname);

If the text doesn't fit, snprintf writes as much as fits, always ends it with '\0', and returns how many characters it would have needed:

int copy_text(char t[], size_t size, const char *s) {
    return snprintf(t, size, "%s", s);
}

char tiny[8];
int needed = copy_text(tiny, sizeof tiny, "Konstantinas");
/* tiny = "Konstan", needed = 12 */

needed >= sizeof tiny means the text was cut.

Why through a function? If you wrote snprintf(tiny, sizeof tiny, "%s", "Konstantinas") inside main, GCC on Linux (and GitHub CI) sees in advance that the text won't fit and, with -Werror, refuses to compile: '%s' directive output truncated writing 12 bytes into a region of size 8. The function gets the text as a parameter, so the length is only known at run time – just like text the user types.

strcpy(t, s) and strcat(t, s) copy and append too, but don't check the size: if s is longer, they write past the array. This course doesn't use them.

Comparing: strcmp, not ==

if (name == "Ona")          /* compares addresses, not text */
error: comparison with string literal results in unspecified behavior [-Werror=address]

== compares whether two arrays are in the same place. Text is compared by strcmp(a, b):

strcmp(a, b) means
< 0 a comes before b
== 0 equal
> 0 a comes after b
if (strcmp(name, "Ona") == 0) { ... }

Check only the sign: strcmp doesn't have to return exactly -1 or 1.

strcmp compares bytes. For Latin letters that is alphabetical order (capitals come before lowercase), but Lithuanian letters in UTF-8 start with a byte bigger than any Latin one, so "Ąžuolas" ends up after "Zita".

Searching: strchr and strcspn

  • strchr(s, ' ') is a pointer to the first space in the string, or NULL if there is none. strchr(full, ' ') + 1 is the text after the space.
  • strcspn(s, "\r\n") is how many bytes from the start are neither \r nor \n. It's a handy way to cut off a line's end: s[strcspn(s, "\r\n")] = '\0'; – you'll need it in step 4.

Characters: <ctype.h>

function true when
isdigit(c) '0'–'9'
isalpha(c) a Latin letter
isspace(c) a space, \t, \n and so on
toupper(c) returns the capital letter

These functions expect an unsigned char value, so a char is converted: isdigit((unsigned char)s[i]). Lithuanian letters are 2 bytes, so toupper leaves them alone: "žalias" becomes "žALIAS".

Walking a string

The loop goes up to '\0', not to the end of the array:

for (int i = 0; s[i] != '\0'; i++) {
    ...
}

That's how strlen itself works: in step 3 you write it yourself.

practice 05 main.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#include "input.h"
/* Whether the grade is valid.
After: returns 1 if grade is from 1 to 10, otherwise 0. */
int is_valid(int grade) {
return grade >= 1 && grade <= 10;
}
/* Asks for a grade until a valid one is entered.
After: the returned grade is from 1 to 10. */
int read_grade(void) {
int grade = read_int("Grade: ");
while (!is_valid(grade)) {
printf("Grade must be between 1 and 10.\n");
grade = read_int("Grade: ");
}
return grade;
}
/* Prints the grade in words.
Before: grade is from 1 to 10. */
void print_in_words(int grade) {
assert(is_valid(grade));
switch (grade) {
case 10:
printf("Excellent\n");
break;
case 9:
printf("Very good\n");
break;
case 8:
printf("Good\n");
break;
case 7:
printf("Fair\n");
break;
case 6:
printf("Satisfactory\n");
break;
case 5:
printf("Weak\n");
break;
default:
printf("Unsatisfactory\n");
break;
}
}
/* Rounds to a whole number.
Before: x >= 0.
After: the nearest whole number; x.5 is rounded up. */
int round_to_int(double x) {
assert(x >= 0);
return (int)(x + 0.5);
}
void run_tests(void) {
assert(is_valid(1));
assert(is_valid(10));
assert(!is_valid(0));
assert(!is_valid(11));
assert(round_to_int(0) == 0);
assert(round_to_int(7.49) == 7);
assert(round_to_int(7.5) == 8);
}
int main(void) {
run_tests();
int count = read_int("How many grades? ");
while (count < 1) {
printf("At least one grade is needed.\n");
count = read_int("How many grades? ");
}
int sum = 0;
for (int i = 1; i <= count; i++) {
printf("%d. ", i);
int grade = read_grade();
print_in_words(grade);
sum += grade;
}
double average = (double)sum / count;
printf("Average: %.2f\n", average);
printf("Rounded: %d\n", round_to_int(average));
return 0;
}