0

In this code I use a for-loop that still checks for '\0' endings. I need to fix it so the function always takes a length for the string to work with inside the function.

If you can give me some explanation how to use length.

#include <stdio.h>
#include <ctype.h>
#include "dbg.h"

int print_a_message(const char *msg)
{
    printf("A STRING: %s\n", msg);

    return 0;
}

int uppercase(const char *msg)
{
    int i = 0;

    // BUG: \0 termination problems
    for(i = 0; msg[i] != '\0'; i++) {
        printf("%c", toupper(msg[i]));
    }

    printf("\n");

    return 0;
}

int lowercase(const char *msg)
{
    int i = 0;

    // BUG: \0 termination problems
    for(i = 0; msg[i] != '\0'; i++) {
        printf("%c", tolower(msg[i]));
    }

    printf("\n");

    return 0;
}

int fail_on_purpose(const char *msg)
{
    return 1;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Sergiu
  • 61
  • 8
  • 1
    Why on earth is `fail_on_purpose()` a part of your question? The three functions that do have a purpose all return 0 every time. There is seldom (but not never) a point to a function that only returns a single value of 0. These functions should all have a return type of `void` and you could drop the `return 0;` line altogether (or use just `return;`, but it looks a little silly at the end of a function). – Jonathan Leffler Oct 24 '14 at 16:03
  • 2
    I think you may need to learn the [void](http://stackoverflow.com/a/1043107/3913686) keyword.It means your method doesn't return anything - you can drop the **int** before your methods and say void intstead –  Oct 24 '14 at 16:07
  • 2
    For the `print_a_message()` function, see [Is there a way to specify how many characters of a string to print out using `printf()`?](http://stackoverflow.com/questions/2239519/print/2239571#2239571) For the upper case and lower case functions, add the extra argument (`int len`) and change the `for` loop to test for `i < len` instead of `msg[i] != '\0';`. – Jonathan Leffler Oct 24 '14 at 16:07

1 Answers1

2

As @Jonathan Leffler suggests: change the for() loop to terminate based on length rather than finding the null character.

#include <stddef.h>

int uppercase(const char *msg, size_t len)
{
    size_t i = 0;
    for(i = 0; i < len; i++) {
        printf("%c", toupper(msg[i]));
    }
    printf("\n");
    return 0;
}

OTOH, if you need to terminate on length and the null character:

int uppercase(const char *msg, size_t len)
{
    size_t i = 0;
    for(i = 0; msg[i] && i < len; i++) {
        printf("%c", toupper(msg[i]));
    }
    printf("\n");
    return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256