Afjörmun

Question

Solution

Idea

I believe the tricky part for this question is to deal with the input in C. The main algorithm is not that hard. It is just you upper the first letter and iterate all the way till the end, if it isupper(), then turn it to lower letter. Otherwise, just leave it as it is.

Code

https://github.com/mendax1234/Coding-Problems/blob/main/kattis/afjormun/afjormun.c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define MAX_LEN 300

void format_meme(char *line)
{
  line[0] = toupper(line[0]);
  for (long i = 1; line[i] != 0; i += 1)
  {
    if (isupper(line[i]))
    {
      line[i] = tolower(line[i]);
    }
  }
}

int main()
{
  long n;
  scanf("%ld\n", &n);
  char **line = calloc((size_t)n, sizeof(char *));
  if (line == NULL)
  {
    return 1;
  }
  for (long i = 0; i < n; i += 1)
  {
    line[i] = calloc(MAX_LEN, sizeof(char));
    if (line[i] == NULL)
    {
      for (long j = 0; j < i; j += 1)
      {
        free(line[j]);
      }
      free(line);
      return 1;
    }
  }

  for (long i = 0; i < n; i += 1)
  {
    if (fgets(line[i], MAX_LEN, stdin))
    {
      line[i][strcspn(line[i], "\n")] = 0;
    }
  }

  for (long i = 0; i < n; i += 1)
  {
    format_meme(line[i]);
    printf("%s\n", line[i]);
  }
  
  for (long i = 0; i < n; i += 1)
  {
    free(line[i]);
  }
  free(line);
}

Take-away

Read a line in C

To read a line in C, it is "safer" to use fgets(). See more about it in Lec 11 - Strcut & Standard I/O.

char line[MAX_LEN];

if (fgets(line, MAX_LEN, stdin))
{
  line[strcspn(line, "\n")] = 0;
}

MAX_LEN should be the actual length of the string +1 because fgets() may read the \n character!

Note that sometimes this method is not 100% safe. So, the safest way I recommend is to use cs1010 library.

Read an integer with newline

Suppose we input an integer with \n, to read it into a variable using scanf(), use the code below:

int a;
scanf("%d", &a);

Read several integers with newline

This will be a bit tricky. For the first integer, we can still use the method above Read an integer with newline. But for the remaining integers, we should use the following method to read:

scanf("\n%d", &a);

The leading \n is used to consume the \n that is left in the stdin.

Last updated