-3
void encode(char* dst, const char* src) {
    while (1) {
       char ch = *src;
       if (!ch || ch != '0','1','2','3') { //pseudo-code
          *dst = 0;
          return;
       }

size_t count = 1;
       while (*(++src) == ch)
          ++count;

       *(dst++) = ch;
       dst += sprintf(dst, "%zu", count);
}

How can I say, ch does not equal a number.. then return. I am trying to get rid of the infinite loop as well.

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60

3 Answers3

2

Try this:

#include <ctype.h>

void encode(char* dst, const char* src) {
    while (1) {
       char ch = *src;
       if (!isdigit(ch)) { //Should works
          *dst = 0;
          return;
   }
   // Rest of the method
}

isdigit(int) return true if the character is an integer (as '1', '2',..., '9') or false in the other case.

(I suppose that the infinity loop is done on purpose)

YaatSuka
  • 231
  • 1
  • 9
1

Here is a little code i've made for you, it will parse all the src string, and tells if the string is a number or not. The probleme you may have with your while(1) is infinite loop and you're only looking for the first caractere so if I pass 2toto as argument it would say ok it's a number.

This function return true if src if a number and false if not.

#include <stdbool.h>

bool encode(char* dst, const char* src) {
  int i = 0;
  char ch;

  while (src[i] != '\0')
    {
      ch = src[i];
      if (!isdigit(ch)) { //pseudo-code                                                                                                                                                                                
        *dst = 0;
        return false;
      }
      i++;
    }
  return true;
}
Nicolas Guerin
  • 356
  • 2
  • 18
0

isdigit works, but for completion's sake, this is how you would begin to write your own check for char ranges:

void encode(char* dst, const char* src) {
    while (1) {
        char ch = *src;
        // the char numeric value minus the 
        // numeric value of the character '0'
        // should be greater than or equal to
        // zero if the char is a digit,
        // and it should also be less than or
        // equal to 9
        if (!ch || (ch - '0' >= 0 && ch - '0' <= 9)) { 
            *dst = 0;
            return;
        }
        // ...
    }
}

As Nicolas says, you need to guarantee that you'll exit the loop though.

synchronizer
  • 1,955
  • 1
  • 14
  • 37