I have to write a program which input is:
Spring Miles Indie Lie Ego
and the result will be: SMILE
But I have some problems with the input. I don't know the length of the input, so it can be any length.
That's why I use scanf to read every single character. I count the spaces to know the size of the array where I'm going to save the characters I need.
So after these here is my main problem: If I found a space I should save the next character which I read from scanf, but how can I do that? Or do you guys know any other option to solve this problem?
Here's my code so far:
int main()
{
char ch;
int i = 0, count= 0;
while(scanf("%c", &ch) != EOF)
{
if(ch == '\n')
count = 0;
if(ch == ' ')
count++;
char array[count+1];
if(ch == ' ')
array[i++] = ch + 1; // I tried this, but it doesn't work.
}
return 0;
}
If you define char array in the while loop, the array will never be available.If the while loop run 10 times, your code will define 10 char array but on one is available after the while loop done.Bellow is my code
int main() {
char ch;
char array[1024];
int i = 0, count= 0;
int status = 1;
while(scanf("%c", &ch) != EOF) {
if(ch == '\n') {
break;
}
if(ch == ' ') {
status = 1;
continue;
}
if (status == 1) {
status = 0;
array[i++] = ch;
}
}
array[i++] = ' ';
printf("%s", array);
return 0;
}
My code is based on the assumption that the array length will not more length than 1024.We can not know the length of input before others input something.So malloc maybe helps you. Malloc is a function in C.You can use it to manage your main memory.