I've written the code, however I cannot remember how to get the user's input.
The command to run the code is ./rle "HHEELLLLO W"
but in my code, I don't know how to get the code to read the "HHEELLLLO W"
.
If I have a regular printf
function, the code will work and will print H1E1L3O 0W0
but I want it so any user's input can be calculated.
I tried using atoi
but I think I've done it wrong and I don't know how to fix it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RLEN 50
char* encode(char* src)
{
int rLen;
char count[MAX_RLEN];
int len = strlen(src);
char* dest = (char*)malloc(sizeof(char) * (len * 2 + 1));
int i, j = 0, k;
for (i = 0; i < len; i++) {
dest[j++] = src[i];
rLen = 1;
while (i + 1 < len && src[i] == src[i + 1]) {
rLen++;
i++;
}
sprintf(count, "%d", rLen);
for (k = 0; *(count + k); k++, j++) {
dest[j] = count[k];
}
}
dest[j] = '\0';
return dest;
}
int main(int argc, char ** argv)
{
char str[] = atoi(argv[1]);
char* res = encode(str);
printf("%s", res);
getchar();
}
When I compile it, I get this error:
rle.c: In function ‘main’:
rle.c:47:18: error: invalid initializer
char str[] = atoi(argv[1]);
^~~~
rle.c:45:14: error: unused parameter ‘argc’ [-Werror=unused-parameter]
int main(int argc, char ** argv)
^~~~
cc1: all warnings being treated as errors
atoi()
does?atoi()
. Here, you don't need to perform any transformation, check for the count of the incoming arguments, and useargv[1]
as needed.argv[1]
to the function and check the value ofargc
so you don't accidentally passNULL
.atoi
for user input, he hasn't taught us any other methods of get user inputs