jeudi 21 septembre 2017

Comparing Characters in an If Statement

so I just started learning C two days ago and I ran into a problem while working on an assignment. We are meant to take a list of characters from a char array and shorten it through counting consecutive chars and replacing them with numbers. Say "aaaabbbbbccccc" to "a4b5c5". This is the code I have so far:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]){ 
   char letters[999];
   char newString[100];
   char counter[100];
   printf("Please input a string: ");
   fgets(letters, sizeof(letters), stdin);
   int i;
   int count = 1;
   int end = 0;
   for(i=0; i<strlen(letters); i++){
   if(letters[i] != letters[i+1] || letters[i+1] == '\0')
   {
     newString[end] = letters[i];
     end++;
     count = 1;
   }
   else if(letters[i] == letters[i+1])
   {
     count++;
   }
 }
 printf("%s", newString);
 return 0;
}

For some reason this goes through the first if statement an incorrect amount of times, and I cannot figure out why. Does it have to do with the character equality statement?

Aucun commentaire:

Enregistrer un commentaire